You are on page 1of 52

EXPERIMENT NO.

- 08

Aim of the Experiment: -. To create a responsive User Interface

Course Outcome:- Design and develop a responsive user Interface by applying PWA
design technique.

Date of Conduction: Date of Submission :

Implementation Understanding Punctuality & Total


(5) (5) Discipline (15)
(5)

Practical Incharge
PRACTICAL NO. 8

Problem Definition: To create a responsive User Interface

Theory:
Responsive web design is about creating web pages that look good on all devices! A responsive web
design will automatically adjust for different screen sizes and viewports.

What is Responsive Web Design?


Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or
enlarge, a website, to make it look good on all devices (desktops, tablets, and phones):
Setting The Viewport
To create a responsive website, add the following <meta> tag to all your web pages:

Example
<meta name=”viewport” content=width=device-width, initial-scale=1.0>
This will set the viewport of your page, which will give the browser instructions on how to control the
page dimensions and scaling.

Responsive Text Size


The text size can be set with a “vw” unit, which means the “viewport width”
That way the text size will follow the size of the browser window:
Hello World
Resize the browser window to see how the text size scales.
Example
<h1 style=”font-size:10vw”>Hello World</h1>
Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm
wide, 1vw is 0.5cm.
Code:
HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Resume</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>John Doe</h1>
<p>Web Developer</p>
</header>

<section class="about">
<h2>About Me</h2>
<div class="about-content">
<div class="about-text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed imperdiet magna nec elit
aliquet euismod. Donec maximus, sem non sagittis varius, mi justo laoreet magna, et convallis odio
purus ut justo. Integer auctor eros quis sapien volutpat, id feugiat arcu accumsan.</p>
</div>
</div>
</section>

<section class="experience">
<h2>Experience</h2>
<ul>
<li>
<h3>Web Developer</h3>
<p>ABC Company, 2020 - Present</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed imperdiet magna nec elit
aliquet euismod.</p>
</li>
<li>
<h3>Frontend Developer</h3>
<p>XYZ Corporation, 2018 - 2020</p>
<p>Nulla facilisi. Proin non lorem nec odio feugiat cursus. Vivamus eu felis ut ipsum
suscipit condimentum.</p>
</li>
</ul>
</section>

<section class="skills">
<h2>Skills</h2>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>JavaScript</li>
<li>React.js</li>
<li>Node.js</li>
<li>SQL</li>
</ul>
</section>

<section class="projects">
<h2>Projects</h2>
<ul>
<li>
<h3>Portfolio Website</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed imperdiet magna nec elit
aliquet euismod.</p>
</li>
<li>
<h3>E-commerce Website</h3>
<p>Nulla facilisi. Proin non lorem nec odio feugiat cursus. Vivamus eu felis ut ipsum
suscipit condimentum.</p>
</li>
</ul>
</section>

<section class="education">
<h2>Education</h2>
<ul>
<li>
<h3>Bachelor of Science in Computer Science</h3>
<p>University of Example, 2014 - 2018</p>
</li>
</ul>
</section>

<section class="contact">
<h2>Contact</h2>
<p>Email: johndoe@example.com</p>
<p>Phone: +1234567890</p>
<p>LinkedIn: <a href="https://www.linkedin.com/in/johndoe/">John Doe</a></p>
</section>

<footer>
<p>&copy; 2024 John Doe. All rights reserved.</p>
</footer>
</body>
</html>
CSS File:

/* Reset CSS */ .experience li,


*{ .education li,
margin: 0; .skills li,
padding: 0; .projects li {
box-sizing: border-box; margin-bottom: 15px;
} }

/* Global Styles */ .experience h3,


body { .education h3,
font-family: 'Segoe UI', Tahoma, Geneva, .projects h3 {
Verdana, sans-serif; margin-bottom: 5px;
line-height: 1.6; color: #555;
background-color: #f4f4f4; }
color: #333;
} footer {
text-align: center;
header { padding: 10px;
text-align: center; background-color: #2c3e50;
padding: 20px; color: #fff;
background-color: #2c3e50; margin-top: 20px;
color: #fff; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); }
}
.contact a {
header h1 { color: #007bff;
font-size: 2.5em; text-decoration: none;
margin-bottom: 10px; transition: color 0.3s ease;
} }

header p { .contact a:hover {


font-size: 1.2em; color: #0056b3;
} }

.about,
.experience, /* Media Queries */
.education, @media only screen and (max-width: 600px) {
.skills, header h1 {
.projects, font-size: 2em;
.contact { }
background-color: #fff;
margin: 20px auto; header p {
padding: 30px; font-size: 1em;
border-radius: 5px; }
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
} .about,
.experience,
.about h2, .education,
.experience h2, .skills,
.education h2, .projects,
.skills h2, .contact {
.projects h2, padding: 20px;
.contact h2 { }
margin-bottom: 20px; }
color: #333;
}
.experience ul,
.education ul,
.skills ul,
.projects ul {
list-style-type: none;
}

OUTPUT:
Conclusion:
Created a responsive UI by applying PWA design technique.
EXPERIMENT NO. - 09

Aim of the Experiment: -. To deploy Progressive Web App to Git Hub Pages

Course Outcome:- Develop and analyse PWA Features and deploy it over app hosting
solutions

Date of Conduction: Date of Submission :

Implementation Understanding Punctuality & Total


(5) (5) Discipline (15)
(5)

Practical Incharge
PRACTICAL NO. 9

Problem Definition: To deploy Progressive Web App to Git Hub Pages

Theory
Build your PWA:

Develop your PWA using web technologies such as HTML, CSS, and JavaScript.

Implement features like responsiveness, offline functionality using service workers, and a web app
manifest.

2. Create a GitHub Repository:

Log in to GitHub and create a new repository.

Name your repository and choose whether it's public or private.

Initialize the repository with a README file if desired.

3. Push your PWA code to GitHub:

If you haven't already, initialize a Git repository in your local PWA project folder:

git init is a command used to initialize a new Git repository in your local project directory. When you
run git init, Git creates a new repository in the current directory or in the directory specified.

Cmd: git init


3.Stage and commit your changes:

a. git add .: The git add . command is used to stage all changes in the current directory and its
subdirectories for the next commit. It prepares changes to be committed to the Git repository. When
you modify files or create new ones in your project, they are initially in an "unstaged" state. Running
git add . adds all these changes to the staging area, marking them for inclusion in the next commit.

b. git commit -m "message":The git commit -m "message" command is used to save the staged
changes to the Git repository. It creates a new commit with a specified commit message describing the
changes made in that commit. The commit message should be descriptive and concise, explaining what
changes were made and why.

Cmd: git add .


Cmd: git commit -m "Responsive Website"

4.Add your GitHub repository as the remote:

git remote add github <url> adds a remote repository named "github" with the specified URL to your
local Git repository, enabling you to push and pull changes to and from that remote location.
5.Fetch and push URLs for each remote repository:
The command git remote -v displays a list of remote repositories associated with your local Git
repository along with their corresponding URLs. It shows both fetch and push URLs for each remote
repository, allowing you to view where your repository is configured to pull changes from and push
changes to.

6.Successfully upload our project let’s now enable it.


7.Go to Github desktop click on ‘Add local repository’

8.Give a local path of the Project and click on ‘Add repository’


9.Click on Publish Branch

10.Go to setting/Pages click on save


11.Click on the url

Successfully Hosted

Conclusion: hence we have successfully deployed Progressive Web App to Git Hub Pages
EXPERIMENT NO. - 10

Aim of the Experiment: -. To use Google Lighthouse PWA Analysis Tool to test
the PWA functioning.

Course Outcome:- Develop and analyse PWA Features and deploy it over app hosting
solutions

Date of Conduction: Date of Submission :

Implementation Understanding Punctuality & Total


(5) (5) Discipline (15)
(5)

Practical Incharge
PRACTICAL NO. 10
Problem Definition: To use Google Lighthouse PWA Analysis Tool to test the PWA functioning.

Theory:

Lighthouse Viewer:
The Lighthouse Viewer is an online tool used to view and share reports generated by the Lighthouse
auditing tool.
It allows users to upload Lighthouse report files (in JSON format) and view them in a user-friendly
format online.
Users can analyze various aspects of web page performance, accessibility, best practices, and SEO, as
evaluated by Lighthouse.

PageSpeed Insights:
PageSpeed Insights is a web-based tool provided by Google to analyze the performance of web pages.
It uses Lighthouse under the hood to generate reports, but it is specifically tailored for analyzing web
page speed and providing recommendations for optimization.
PageSpeed Insights offers a user-friendly interface where users can enter a web page URL and receive
a detailed report on performance metrics and suggestions for improvement.
1.Click on the inspect

Fig:0.1 PWA Website


2.Go to Lighthouse and click on the Analyze page load

Fig: 0.2 Lighthouse setting


3.Install the Lighthouse Chrome Extension from the Chrome Web Store.
“Click on Add to Chrome”

4.Navigate to the web page you want to audit in Chrome.


Click on the Lighthouse icon next to the Chrome address bar. If you can't find it there, access it
through Chrome's main menu, typically found at the top of the browser window. Click on the
Lighthouse menu to expand it.
Click on Generate report
5.Here you analyze you website and see performance, accessibility, best Practices and SEO

Fig: 0.3 Lighthouse page UI


6.Go to PageSpeed Insights website
7.Paste your website link and click on Analyze

Fig: 0.4 PageSpeed Insight UI


EXPERIMENT NO. - 06

Aim of the Experiment: -. To write and read data into/from firebase

Course Outcome:- Analyze and Build production ready app by incorporating backend
services and deploying on andriod

Date of Conduction: Date of Submission :

Implementation Understanding Punctuality & Total


(5) (5) Discipline (15)
(5)

Practical Incharge
PRACTICAL NO. 6
Problem Definition: To write and read data into/from firebase

Theory:

Writing Data to Firebase Firestore:


Data Structure:
Firebase Firestore is a NoSQL cloud database that stores data in documents, which are organized into
collections. Each document contains a set of key-value pairs, where each value can be a string,
number, boolean, map, array, or timestamp.
Before writing data, you need to decide on the structure of your data. Determine the collections and
documents you'll use and the fields within each document.
Database Reference:
To interact with Firestore, you first need to get an instance of the FirebaseFirestore class using
FirebaseFirestore.getInstance().
You can then create references to collections and documents using methods like collection() and
document().
Writing Data:
To write data to Firestore, you create a Map object containing the data you want to store.
You then use methods like set() or add() to add the data to a document or collection.
Reading Data from Firebase Firestore:
Data Retrieval:
Reading data from Firestore involves retrieving documents or collections based on certain criteria.
You can retrieve a single document using its unique document ID, or you can perform queries to
retrieve multiple documents based on filters and sorting.
Data Listener:
Firestore provides real-time data synchronization, allowing your app to listen for changes to
documents or collections.
You can attach listeners to documents or collections using methods like get() or
addSnapshotListener().
When the data changes, your app is notified, and you can update the UI accordingly.
Handling Data:
Once you receive the data from Firestore, you can extract the values of the fields from each document
and use them in your app.
Handle any errors that may occur during the data retrieval process.
Here's a step-by-step guide:
1.Click on the New Project

2.Click on Empty Views Activity


3.On next window, give Name as “My Application” and select below option and then click on
Finish button

• Language as “Java”

4. To enable Firebase Assistant, go to “Tools” and select “Firebase” option.


5.Firebase Assistant has all the Firebase services that we can add to our program. In order to use
the services, click on the service and then choose option get started link.

• Example: To connect to “Cloud Firestore”, click on Cloud Firestore first and then on the link
– get started with Cloud Firestore.

6.Choose the button to connect to Firebase


7.Click on the Add project

8.You will notice that the application Name is extracted automatically. Click on continue on
current and next window.
9.Click on Continue

9.On configure Google Analytics page, select the account as default account for Firebase and click
on create project.
10.Click on Connect

11.Here Your Android Studio project is connected to your Firebase Android app
12.Go back to Android Studio, there under Firebase assistant, you will see that the Firebase is
connected.

13.This way we can connect any Firebase service to Android SDK. Lets test another service i.e.
Firestore SDK.
● Click on “Add the Cloud Firestore SDK to your app”.
● Click on “Accept changes” button on next window. This will add the dependency
automatically.
14.Create Database in Firebase Console-
a. Click on Firebase Console

15.It will take you to web-browser. Select the project “My Application”.
16.Click on Create database option on next page.

17.Create database in test mode.


Activity_main.xml code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to firebase console and check the data is added there or not."
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constr+
3.0 0aintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java Code:
package com.example.myapplication;

import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore firestore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Make sure this layout file exists
firestore = FirebaseFirestore.getInstance();
yourMethod();
}
private void yourMethod() {
Map<String, Object> user = new HashMap<>();
user.put("firstName", "Doremon");
user.put("lastName", "Nobita");
user.put("description", "Cartoon");

firestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}});}}
OUTPUT:
18.Go to firebase console and check if the data is added there. Reload (refresh the page) the Cloud
Firestore.

Conclusion: we have learnt connect and how to write and read data into/from firebase
EXPERIMENT NO. - 07

Aim of the Experiment: -. To test and deploy production ready Flutter App on Android
platform.

Course Outcome:- Analyze and Build production ready app by incorporating backend
services and deploying on andriod

Date of Conduction: Date of Submission :

Implementation Understanding Punctuality & Total


(5) (5) Discipline (15)
(5)

Practical Incharge
PRACTICAL NO. 7

Problem Definition: To test and deploy production ready Flutter App on Android
platform.

Compiler / Tool : Flutter sdk, Android studio

Theory:

Implementation:

1. Make App ready


2. Set app icon
3. Set app name
4. Set unique application id
5. Build and release app
6. Create Google developer account
7. Prepare app for review
8. Roll out app to play store

Steps:

1. Set App Icon


Visit https://docs.flutter.dev/deployment/android and scroll to adding a
launcher icon.
Visit https://romannurik.github.io/ and select icon for the app, and
download the file.
Open flutter_launcher_icon on website. Copy the setup config file and paste in
pubspec.yaml under dependencies.

Copy run the package from website and run in terminal.


2.App Name

Open https://pub.dev/packages/rename and copy the installation and execute in terminal.

3.Set Unique Application ID

Copy defualt usage to create unique id.


4. Publish to Playstore
Build & Release App
Create new folder in android named “key.properties”.

5.Copy paste the keystore code from website and paste in key.properties and change the
password.
6.Copy the upload keystore for windows and run in terminal. Save the upload keystroke in
android folder.

7.Copy the configure signing in gradle and paste in build.cratle


8.Run Flutter Clean in terminal to delete any previous build

2D To-Do-List_App
Main.dart File:

import 'package:flutter/material.dart';

import 'game_page.dart';

void main() {

runApp(const MyApp());

class MyApp extends StatelessWidget {

const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.

@override

Widget build(BuildContext context) {

return MaterialApp(
title: 'ToDo App',

debugShowCheckedModeBanner:

false, theme: ThemeData(

primarySwatch: Colors.blue,

),

home: GamePage(),

);

import 'dart:ui'; children: [


Container(
import 'package:flutter/material.dart'; padding: EdgeInsets.symmetric(
horizontal: 20,
import '../model/todo.dart'; vertical: 15,
import '../constants/colors.dart'; ),
import '../widgets/todo_item.dart'; child: Column(
children: [
searchBox(),
class Home extends StatefulWidget { Expanded(
Home({Key? key}) : super(key: key); child: ListView(
@override children: [
State<Home> createState() => Container(
_HomeState(); margin: EdgeInsets.only(
} top: 50,
bottom: 20,
class _HomeState extends State<Home> ),
{ child: Text(
final todosList = ToDo.todoList(); 'All ToDos',
List<ToDo> _foundToDo = []; style: TextStyle(
final _todoController = fontSize: 30,
TextEditingController(); fontWeight: FontWeight.w500,
),
@override ),
void initState() { ),
_foundToDo = todosList; for} (ToDo todoo in _foundToDo.reverse
super.initState();
} ToDoItem(
@override
todo: todoo,
Widget build(BuildContext context) {
onToDoChanged:
), _handleToChange,
return Scaffold(
onDeleteItem: _deleteToDoItem,
backgroundColor: tdBGColor,
appBar: _buildAppBar(),
body: Stack(
], onPressed: () {
), _addToDoItem(_todoController.text);
), },
Align( style: ElevatedButton.styleFrom(
alignment: Alignment.bottomCenter, primary: tdBlue,
child: Row(children: [ minimumSize: Size(60, 60),
Expanded( elevation: 10,
child: Container( ),
margin: EdgeInsets.only( ),
bottom: 20, ),
right: 20, ]),
left: 20, ),
), ],
padding: EdgeInsets.symmetric( ),
horizontal: 20, );
vertical: 5, }
),
decoration: BoxDecoration( void _handleToDoChange(ToDo todo) {
color: Colors.white, setState(() {
boxShadow: const [ todo.isDone = !todo.isDone;
BoxShadow( });
color: Colors.grey, }
offset: Offset(0.0, 0.0),
blurRadius: 10.0, void _deleteToDoItem(String id) {
spreadRadius: 0.0, setState(() {
), todosList.removeWhere((item) => item.id == id);
], });
borderRadius: }
BorderRadius.circular(10), void _addToDoItem(String toDo) {
), setState(() {
child: TextField( todosList.add(ToDo(
controller: _todoController, id: DateTime.now().millisecondsSinceEpoch.
decoration: InputDecoration( toString(),
hintText: 'Add a new todo todoText: toDo,
item', ));
border: InputBorder.none), });
), _todoController.clear();
), }
),
Container( void _runFilter(String enteredKeyword) {
margin: EdgeInsets.only( List<ToDo> results = [];
bottom: 20, if (enteredKeyword.isEmpty) {
right: 20, results = todosList;
), } else {
child: ElevatedButton( results = todosList
child: Text( .where((item) => item.todoText!
'+', .toLowerCase()
style: TextStyle( .contains(enteredKeyword.toLowerCase.to
fontSize: 40, List();
), }
),
setState(() { SAppBar _buildAppBar() {
_foundToDo = results; return AppBar(
}); backgroundColor: tdBGColor,
} elevation: 0,
title: Row(mainAxisAlignment:
Widget searchBox() { MainAxisAlignment.spaceBetween, children: [
return Container( Icon(
padding: EdgeInsets.symmetric(horizontal: 15), Icons.menu,
decoration: BoxDecoration( color: tdBlack,
color: Colors.white, size: 30,
borderRadius: BorderRadius.circular(20), ),
), Container(
child: TextField( height: 40,
onChanged: (value) => _runFilter(value), width: 40,
decoration: InputDecoration( child: ClipRRect(
contentPadding: EdgeInsets.all(0), borderRadius: BorderRadius.circular(20),
prefixIcon: Icon( child: Image.asset('assets/images/avatar.
Icons.search, jpeg'),
color: tdBlack, ),
size: 20, ),
), ]),
OUTPUT:

Conclusion: We have learnt how to test and deploy production ready Flutter App on Android
platform.
INNOVATIVE EXPERIMENT

Aim: Android Application to generate Calculator

Main.dart:
import 'package:flutter/material.dart';
import 'calculator_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Calculator',
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: const CalculatorScreen(),
);
}
}

button_values.dart:
class Btn {
static const String del = "D";
static const String clr = "C";
static const String per = "%";
static const String multiply = "×";
static const String divide = "÷";
static const String add = "+";
static const String subtract = "-";
static const String calculate = "=";
static const String dot = ".";

static const String n0 = "0";


static const String n1 = "1";
static const String n2 = "2";
static const String n3 = "3";
static const String n4 = "4";
static const String n5 = "5";
static const String n6 = "6";
static const String n7 = "7";
static const String n8 = "8";
static const String n9 = "9";

static const List<String> buttonValues = [


del,
clr,
per,
multiply,
n7,
n8,
n9,
divide,
n4,
n5,
n6,
subtract,
n1,
n2,
n3,
add,
n0,
dot,
calculate,
];
}

Calculator_screen.dart:
import
'package:calculator_app/button_values.dart'; case Btn.multiply:
import 'package:flutter/material.dart'; result = num1 * num2;
break;
class CalculatorScreen extends StatefulWidget { case Btn.divide:
const CalculatorScreen({super.key}); result = num1 / num2;
break;
@override default:
State<CalculatorScreen> createState() => }
_CalculatorScreenState();
} setState(() {
number1 = result.toStringAsPrecision(3);
class _CalculatorScreenState extends
State<CalculatorScreen> { if (number1.endsWith(".0")) {
String number1 = ""; // . 0-9 number1 = number1.substring(0,
String operand = ""; // + - * / number1.length - 2);
String number2 = ""; // . 0-9 }

@override operand = "";


Widget build(BuildContext context) { number2 = "";
final screenSize = });
MediaQuery.of(context).size; }
return Scaffold(
body: SafeArea( // ##############
bottom: false, // converts output to %
child: Column( void convertToPercentage() {
children: [ // ex: 434+324
// output
Expanded(
child: SingleChildScrollView( if (number1.isNotEmpty &&
reverse: true, operand.isNotEmpty && number2.isNotEmpty)
child: Container( {
alignment: Alignment.bottomRight, // calculate before conversion
padding: const EdgeInsets.all(16), calculate();
child: Text( }

"$number1$operand$number2".isEmpty if (operand.isNotEmpty) {
? "0" // cannot be converted
: "$number1$operand$number2", return;
style: const TextStyle( }
fontSize: 48,
fontWeight: FontWeight.bold, final number = double.parse(number1);
), setState(() {
textAlign: TextAlign.end, number1 = "${(number / 100)}";
), operand = "";
), number2 = "";
), });
), }
// buttons // ##############
Wrap( // clears all output
children: Btn.buttonValues void clearAll() {
.map( setState(() {
(value) => SizedBox( number1 = "";
width: value == Btn.n0 operand = "";
? screenSize.width / 2 number2 = "";
: (screenSize.width / 4), });
height: screenSize.width / 5, }
child: buildButton(value),
), // ##############
) // delete one from the end
.toList(), void delete() {
) if (number2.isNotEmpty) {
], // 12323 => 1232
), number2 = number2.substring(0,
), number2.length - 1);
); } else if (operand.isNotEmpty) {
} operand = "";
Widget buildButton(value) { } else if (number1.isNotEmpty) {
return Padding( number1 = number1.substring(0,
padding: const EdgeInsets.all(4.0), number1.length - 1);
child: Material( }
color: getBtnColor(value),
clipBehavior: Clip.hardEdge, setState(() {});
shape: OutlineInputBorder( }
borderSide: const BorderSide( // #############
color: Colors.white24, // appends value to the end
), void appendValue(String value) {
borderRadius: // number1 opernad number2
BorderRadius.circular(100), // 234 + 5343
),
child: InkWell( // if is operand and not "."
onTap: () => onBtnTap(value), if (value != Btn.dot && int.tryParse(value)
child: Center( == null) {
child: Text( // operand pressed
value, if (operand.isNotEmpty &&
style: const TextStyle( number2.isNotEmpty) {
fontWeight: FontWeight.bold, // TODO calculate the equation before
fontSize: 24, assigning new operand
), calculate();
), }
), operand = value;
), }
), // assign value to number1 variable
); else if (number1.isEmpty || operand.isEmpty)
} {
// ######## // check if value is "." | ex: number1 = "1.2"
void onBtnTap(String value) { if (value == Btn.dot &&
if (value == Btn.del) { number1.contains(Btn.dot)) return;
delete(); if (value == Btn.dot && (number1.isEmpty
return; || number1 == Btn.n0)) {
} // ex: number1 = "" | "0"
value = "0.";
if (value == Btn.clr) { }
clearAll(); number1 += value;
return; }
} // assign value to number2 variable
else if (number2.isEmpty ||
if (value == Btn.per) { operand.isNotEmpty) {
convertToPercentage(); // check if value is "." | ex: number1 = "1.2"
return; if (value == Btn.dot &&
} number2.contains(Btn.dot)) return;
if (value == Btn.dot && (number2.isEmpty
if (value == Btn.calculate) { || number2 == Btn.n0)) {
calculate(); // number1 = "" | "0"
return; value = "0.";
} }
number2 += value;
appendValue(value); }
}
setState(() {});
// ############## }
// calculates the result
void calculate() { // ########
if (number1.isEmpty) return; Color getBtnColor(value) {
if (operand.isEmpty) return; return [Btn.del, Btn.clr].contains(value)
if (number2.isEmpty) return; ? Colors.blueGrey
final double num1 = double.parse(number1); :[
final double num2 = double.parse(number2); Btn.per,
var result = 0.0; Btn.multiply,
switch (operand) { Btn.add,
case Btn.add: Btn.subtract,
result = num1 + num2; Btn.divide,
break; Btn.calculate,
case Btn.subtract: ].contains(value)
result = num1 - num2; ? Colors.orange
break; : Colors.black87;
}
}
OUTPUT:

Conclusion: We have learnt how to developed android application to generate calculator using flutter.

You might also like