0% found this document useful (0 votes)
3 views143 pages

Note2 Flutter

Flutter is an open-source UI toolkit developed by Google for building natively compiled applications across mobile, web, and desktop platforms from a single codebase. It utilizes Dart programming language and features a unique architecture where everything is a widget, allowing for complex user interfaces through a widget tree structure. The document also covers installation, basic app creation, and the properties of key widgets like MaterialApp and Scaffold.

Uploaded by

jemica003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views143 pages

Note2 Flutter

Flutter is an open-source UI toolkit developed by Google for building natively compiled applications across mobile, web, and desktop platforms from a single codebase. It utilizes Dart programming language and features a unique architecture where everything is a widget, allowing for complex user interfaces through a widget tree structure. The document also covers installation, basic app creation, and the properties of key widgets like MaterialApp and Scaffold.

Uploaded by

jemica003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

What is Flutter ?

Flutter is an open source framework & UI toolkit for building natively compiled applications
for mobile, web, desktop, and embedded devices from a single code base. Flutter was Initially
developed by Google and is now managed by ECMA standard (European Computer Manufacturers
Association).

History of Flutter
The first version of Flutter was announced in the year 2015 at the Dart Developer summit and was
initially code-named "Sky". After the announcement of Flutter, the first Flutter Alpha version (v-0.06)
was released in May 2017.

Examples

eBay Motors​

eBay Motors, owned by eBay, is a standout example of a large-scale eCommerce


platform among apps built with Flutter.

New York Times

Hamilton Musical

To increase users' engagement and possibly prolong their interest in the spectacle,
Hamilton's creators decided to develop an app that gives users additional ways to
interact with their favorite characters.

MyBMW

MyBMW app enables BMW owners to interact with their cars—lock, unlock, locate,
monitor, and navigate using their mobile devices.

Why Flutter ?

When it comes to developing mobile applications, there are two main platforms - android & iOS.
Android was using its own native framework based on Java and Kotlin language, whereas iOS was
using Objective-C & Swift language, which meant traditionally an application deployed on android had
to be re-coded to get it deployed on iOS. To overcome this complexity, several cross-platform
frameworks came into existence. A cross-platform development framework has the ability to code in
one language and deploy it in multiple platforms like Android, iOS, and Desktop. Flutter stands out as
a cross-platform development tool which helps deploying its application in Desktop, Android and iOS
from a single code base. Flutter, developed using Dart programming language shares several features
of other programming languages like Kotlin, Swift, Jscript, etc.. and thus can be easily
trans-compiled(transpiled) into other languages including JavaScript code.

Cross platform examples


React Native
Flutter
Ionic
Cordova
Xamarin

What makes Flutter unique?

Flutter is different from other frameworks because it neither uses WebView(A browser engine
contained within an application that allows programmer to write the bulk of the application using
HTML, JavaScript and CSS) nor the OEM widgets(original equipment manufacturer widgets) that is
shipped with the device. Dart uses its own ‘high-performance’ rendering engine to draw widgets.

Understanding the Flutter architecture

The architecture of the Flutter framework.


Widgets

”In Flutter, Everything is a widget” is the core concept of the Flutter framework. Widgets are basically
user interface components to create the user interface of an application.
In Flutter, the application itself is a widget, it is the top-level widget and its UI(user interface) is built
using one or more children (widget). This composability helps us to create a user interface of any
complexity. A Flutter widget tree is similar to the DOM (Document Object Model) on the browser,
which is also a tree-structure.
StatelessWidget and StatefulWidget. These are two widgets that are the base of all other widget
types
Concept of State
The widget which contains the code for a single screen of the app can be of just two types —
- Stateless
- Stateful
Stateless
Stateless widgets do not require mutable state, i.e., it is immutable. Stateless widgets cannot change
their state during the runtime of the app, which means it cannot be redrawn while the app is in
action. Stateless Widget are defined by overriding the “build” method. This build method takes in a
“BuildContext” as the parameter and returns a widget. This is the place where you can design the UI
of this screen, which is Stateless.
In Stateless widget, The “build” method can be called only ONCE while the app is in action, which is
responsible for drawing the widgets on to the device screen.
TIPS: You can quickly build a Stateless Widget in Android Studio by using the shortcut “stl”.
If you want to redraw the Stateless Widget, then you will need to create a new instance of the widget.
Stateful
Stateful widgets have a mutable state, i.e., they can be re-drawn multiple times within its lifetime
while the app is in action. It is defined by overriding the “createState” method, instead of the “build”
method, which returns the instance of the class “_StartScreenState”.
The class “_StartScreenState” extends from State<> which takes “StartScreen” as a template input.
Now, this “_StartScreenState” overrides the “build” method and returns a widget. This is where you
can define the UI of the app, which is Stateful. As it is a Stateful widget you can call the build method
any number of times, which will redraw the widgets on the screen.
Calling the build method
The “setState” method is used to call the build method, which will, in turn, redraw the widgets. This
is the most important method you will need to use with any Stateful widget, to really use the
statefulness of the widget.
StatefulWidget will be auto re-rendered whenever its internal state is changed. The re-rendering is
optimized by finding the difference between old and new widget UI and rendering only the necessary
changes.
TIPS: You can quickly build a Stateful Widget in VS Code or Android Studio by using the shortcut “stf”.
Gestures
Flutter widgets support interaction through a special widget, GestureDetector. GestureDetector is an
invisible widget having the ability to capture user interactions such as tapping, dragging, etc., of its
child widget. Many native widgets of Flutter support interaction through the use of GestureDetector.
We can also incorporate interactive feature into the existing widget by composing it with
the GestureDetector widget. We will learn the gestures separately in the upcoming chapters.

Layers
The most important concept of Flutter framework is that the framework is grouped into multiple
category in terms of complexity and clearly arranged in layers of decreasing complexity. A layer is
build using its immediate next level layer. The top most layer is widget specific to Android and iOS.
The next layer has all flutter native widgets. The next layer is Rendering layer, which is low level
renderer component and renders everything in the flutter app. Layers goes down to core platform
specific code
The following points summarize the architecture of Flutter –

In Flutter, everything is a widget and a complex widget is composed of already existing widgets.
Widget also can be considered as a data type provided by Flutter, Just like the other data types of dart.

Interactive features can be incorporated whenever necessary using GestureDetector widget.


Flutter offers layered design so that any layer can be programmed depending on the complexity of
the task.

Flutter widget tree


Everything in Flutter is a widget. Whether it is a container, text, button, providers, image, etc.,
everything is virtually a widget, no matter if they display a UI in the app or not.
The UI or display in Flutter comprises stacks of widgets popularly called a widget tree. If you are
coming from a JavaScript background or have used either Reactjs or Angular, you will understand this.
In Reactjs, the UI is made up of a tree of components. Each component is responsible for a small unit
of the entire UI.
In Flutter, it is not a component, rather it is a widget. A widget is responsible for a small unit in a
Flutter app. As in SPAs, the widget tree has a root widget. This is the widget from which other widgets
are stacked upon, meaning there will also be parent widgets and child widgets.
A widget that renders another widget is the parent widget, which renders the the child widget. The
MyApp widget is usually the root widget, just like the App component is usually the root component
in React.

Let’s see an example:


MyApp

Container

Row

----------

Text FlatButton
In the above diagram, we can see a widget tree in a Flutter app. The MyApp is the root widget, and it
is the parent of all the widgets in the tree. So, we can say that MyApp is the parent of Container, and
that the Container is the parent of Row and the child of MyApp. The Row is the child of Container and
parent of Text and FlatButton. Text and FlatButton are the children of Row.
Now that we can see the relationship, let’s see how BuildContext comes in.
What is BuildContext?
BuildContext is a locator that is used to track each widget in a tree and locate them and their position
in the tree. The BuildContext of each widget is passed to their build method and the build method
returns the widget tree a widget that it renders.
Each BuildContext is unique to a widget. This means that the BuildContext of a widget is not the same
as the BuildContext of the widgets returned by the widget.
MyApp {
build(BuildContext ctx) {
return Container(
child: Row(
children: [
Text(),
FlatButton()
]
)
)
}
}
The BuildContext in the MyApp widget is different from the BuildContext in the Container widget and
all widgets in its tree. So, the BuildContext of the MyApp is the BuildContext parent of the
BuildContexts of its child widgets.
The MyApp has its BuildContext, Container has its BuildContext, Row has its BuildContext, and Text
and FlatButton have their own BuildContext, all of which are unique to each other.

How Flutter and dart code gets compiled to native apps

Transpiler
A traditional compiler translates from a higher level programming language to a lower level
programming language. For example, a source-to-source translator may perform a translation of a
program from Python to JavaScript, while a traditional compiler translates from a language like C to
assembler or Java to bytecode.

The SDK includes a compiler that complies our dart code and builds an ‘apk’ file and widget libraries to
create widgets
Using the Dart language allows Flutter to compile the source code ahead-of-time to native code. The
engine's C/C++code is compiled with Android's NDK or iOS' LLVM. Both pieces are wrapped in a
“runner” Android and iOS project, resulting in an apk or ipa file respectively.

Downloading & Installation of Flutter and Andriod Studio

Things you need to install

Flutter: You will get a detailed guide on how to install Flutter on your machine from this link
‘[Link] Please follow the installation guide thoroughly and don’t
dare to skip any steps.

Android Studio: Another thing that you must install is the Android Studio ‘
[Link] ‘, because with it comes the Android toolchain, which is needed
to run any Android app on a device and also for some Android customizations [ Like setting proper
launcher icon for the app and some other things ], and if you want to use the Android emulator for
testing your app.
Note: Add plug in Flutter in android studio
MAC:
Xcode: If you’re on a Mac, you should install Xcode, which you can get from the app store here
‘[Link] ‘. You will be needing Xcode to run and test iOS
side of your Flutter app as along with it comes the iOS simulator.

Which IDE should you use

There are two famous IDE(s) used for Flutter Development:


1) Android Studio

2) VS Code

Both are really good for Flutter Development and have their own advantages and disadvantages. For
the Android developers out there they would be more comfortable with Android Studio so they
should go with it. And if you want to publish only the Android version of the app, then you should
definitely go with the Android Studio.
VS Code is known as a very powerful code editor, so there is a strong point to go with it as it would
always remain updated with the latest version of Flutter and Dart.

Installing Android SDK command-line tools

Close project > customize > All Settings > SDK Tools > Android SDK command-line tools > OK > apply

In cmd prompt run

flutter config --android-studio-dir="c:\Program Files\Android\Android Studio"

How to clone a Flutter app from GIThub

- Inside github, click on CODE > under clone click on copy sign
- In flutter, click on File>new>Project from Version Control>paste the copied url here

Flutter Basics

Creating a New Project

Click on File menu, select new, select new flutter project


Once the files and folders are created, delete everything from [Link] under lib directory.
Now we have to type everything from beginning
An Overview of the Generated Files & Folders
Under the lib folder you will find ‘[Link]’, which has void main(), the first function that will be
executed when the app is run is main() which will invoke runApp() a function that resides in the file
‘[Link]’ which is a part of flutter library.
Import statement, ‘Import'package:flutter/[Link]' imports [Link] from library for
material design and will import all the associated widgets from Material package.
Remove all codes from ‘[Link]’ and type in the below code to create an app from scratch.

Building an App From Scratch: A Simple App with a single child widget

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
body: Container(
child: Text("Flutter App"),
),
),
);
}
}

Running the App on an Emulator

​ Click on AVD Manager option from the top right menu bar.

​ Message “Unable to Locate ADB” can be ignored, this is Android Debug Bridge or ADB is a utility
that allows you to use your mobile devices using the USB cable from your PC. this really is a
utility which 100% works.
​ To run the app, click on [Link] option from the right side top menu bar. Debug run is for
development stage of an app as it will help to identify and fix bugs easily. Another way to fix bugs
is by using the check points, which will pause execution at run time at several points.

How the above code works


The runApp() function takes the given Widget and makes it the root of the widget tree. In the above
example, the widget tree consists of two widgets, the Center widget and its child, the Text widget. The
framework forces the root widget to cover the screen(Center in this code), which means the text
“Hello, world” will end up centered on screen. The text direction needs to be specified in this instance;
when the MaterialApp widget is used, this is taken care of by the widget, which we will look into in the
next example.

For more information on Widgets and its properties: visit ‘


[Link] ‘

Class Constructors & Named Arguments


The below example creates an object ‘app’ of the class ‘MaterialApp

Similarly we can create flutter objects by initiating flutter classes:-

import 'package:flutter/[Link]';
void main() {
MaterialApp app = MaterialApp(
title: "Learning Exercise",
home: Scaffold(
body: Container(
child: Center(
child: Text("Learning exercise app"),
),
),
),
);
runApp(app);
}

Other way:
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

main() {
runApp(
MaterialApp(
title: "Learning",
home: Scaffold(
appBar: AppBar(
title: Text("Learning App"),
),
body: Container(
child: Center(
child: Text("Learning app"),
),
),
),
),
);
}

Properties of MaterialApp

MaterialApp() widget: Let us have a look at the different properties of the MaterialApp widget.
title: This property is used to provide a short description of the application to the user. When the user
press the recent apps button on mobile the text proceeded in title is displayed.
theme: This property is used to provide the default theme to the application like the theme-color of
the application. For this, we use the inbuilt class/widget named ThemeData(). In Themedata() widget
we have to write the different properties related to the theme. Here we have used the primarySwatch
which is used to define the default themecolor of the application. To choose the color we have used
Colors class from the material library. In ThemeData() we can also define some other properties like
TextTheme, Brightness(Can enable dark theme by this), AppBarTheme, and many more.
home: It is used for the default route of the app means the widget defined in it is displayed when the
application starts normally. Here we have defined the Scaffold widget inside the home property. Inside
the Scaffold we define various widgets.

Scaffold

Scaffold is another widget class in flutter which provides many other widgets or we can say
APIs(Application Programming Interface.). Scaffold will expand or occupy the whole device screen.
Scaffold will provide a framework to implement MaterialApp() widget. Some of the properties of the
Scaffold widget are appBar, body, floatingActionButton, backgroundColor, etc.
resizeToAvoidBottomInsets: This property takes in a boolean value as the object. If set to true then the
floating widgets on the scaffold resize themselves to avoid getting in the way of the on-screen
keyboard.

SafeArea
Observe where the text was shown in the previous app. Wrap Container with SafeArea()

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
body: SafeArea(
child: Container(
child: Text("Flutter App"),
),
),
),
);
}
}

AppBar and debugShowCheckedModeBanner

import 'package:flutter/[Link]';

void main() {
runApp(
MaterialApp(
title: 'Learning app',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: Center(child: Text('Learning Material App'))),
body: SafeArea(
child: Container(
child: Text("Flutter App"),
),
),
),
),
);
}

What is a Container?

Container is a convenience widget that combines common painting, positioning, and sizing of widgets.
A Container class can be used to store one or more widgets and position it on the screen according to
our convenience. Its common properties are child, color, height & width, margin, padding, alignment,
decoration, transform, constraints, clipBehaviour, foreground`dDecoration.

Hot Reload
For hot reload to work we have to use Stateless or Statefull widget, so let us make the above stateless.
At the bottom of the below code, type ‘stl’ and press <enter>, here type name “MyApp”, so everything
will automatically change into that name.
- add background color for scaffold
- add background and foreground colour for AppBar
- call ‘MyApp()’ inside ‘runApp’

How to create a Custom Widget and more on CONTAINER WIDGET

Right click on ‘lib’ create a new folder ‘Widgets’ - create a new file named ‘[Link]’ in this
folder. import 'package:my_app/widgets/[Link]'; into [Link] file

The following codes will be in each file listed below:-

[Link]
import 'package:my_app/widgets/[Link]';
import 'package:flutter/[Link]';

void main() {
runApp( SomeApp());
}

[Link] (tip: create below using ‘stl’)

Start a container with no child, it will try to be as big as possible, eg:- occupying the whole screen as it
is inside a scaffold in our code

import 'package:flutter/[Link]';

class SomeApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Text("Some App"),
),
body: Container(
child: Text("Some App"),
),
),
);
}
}

- add color and do HR(hot reload)


- add “child: Text("Antonys App"),” - do hr and see that the shrinks to size of the child and result on top
left.
- wrap container with a ‘Widget’ and rename it as ‘SafeArea’: Safe Area occupies the space visible to
the user excluding the edges
- add height & width
- add decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
),

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
),
),
);
}
}

- Change the size of container to height 200, width 200, border pixel to 10, and place the container to
the center of the screen by wraping it with Center Widget
- add an AppBar with some contents displayed in the middle.
- Change the background and foreground color of the appbar,
- Add Margin & Padding

import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
body: SafeArea(
child: Container(
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
height: 200,
width: 200,
margin: [Link](120, 200, 120, 200),
//color: [Link],//cannot provide both color & decoration
child: Text("Antony's App"),
padding: [Link](45, 80, 5, 15),
),
),
),
);
}
}

- make boxdecoration border radius circular


“ borderRadius: [Link](25) “


import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: Container(
width: 200,
height: 400,
margin: [Link](100, 80, 50, 50),
padding: [Link](20, 50, 10, 50),
decoration: BoxDecoration(
borderRadius: [Link](100),
color: [Link],
border: [Link](
color: [Link],
width: 10,
),
),
child: Center(
child: Text("Scope learning App"),
),
),
),
),
);
}
}

- add transform rotation

import 'package:flutter/[Link]';

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: Container(
width: [Link],
height: 200,
margin: [Link](50, 180, 0, 0),
padding: [Link](30),
transform: [Link](0.1), // rotation on z axis, try different variations
decoration: BoxDecoration(
borderRadius: [Link](25),
color: [Link],
border: [Link](
color: [Link],
width: 10,
),
),
child: Center(
child: Text(
"Scope learning App",
),
),
),
),
),
);
}
}
Task:

- Remove Center for Text() and add “alignment: [Link],”


- inside Text, add “style: TextStyle(fontSize: 25), “
- Remove Boxdecoration margin(border all)
- add appbar with text “Container example”

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
"Container example",
style: TextStyle(fontSize: 25),
)),
),
body: SafeArea(
child: Container(
alignment: [Link],
width: 400,
height: 200,
margin: [Link](50, 180, 0, 0),
padding: [Link](30),
transform: [Link](
0.1), // rotation on z axis, try different variations
decoration: BoxDecoration(
borderRadius: [Link](25),
color: [Link],
),
child: Text(
"Scope learning App",
style: TextStyle(fontSize: 30),
),
),
),
),
);
}
}

Adding a network Image to the app:

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("I am a burning Fire")),
),
// ignore: prefer_const_constructors
body: Center(
child: Image(
image: NetworkImage(

"[Link]
cSw&usqp=CAU"),
),
),
),
),
);
}

Adding an Image through the asset image:

- Image to be made available in the hard disk (download)


- Create directory ‘images’ under the project folder
- Drag and drop the image into the ‘images’ directory
- Update the path in [Link] file, make sure that the alignment is correct. Firstly remove all the
comments from the file and ensure it is done as below:-

flutter:
uses-material-design: true
assets:
- images/[Link]

- Click on Pub get

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("I am Fire")),
),
// ignore: prefer_const_constructors
body: Center(
child: Image(
image: AssetImage("images/[Link]"),
),
),
),
),
);
}
Columns & Rows

import 'package:flutter/[Link]';
void main() {
runApp(AntonysApp());
}
class AntonysApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
"Column example",
style: TextStyle(fontSize: 25),
)),
),
body: SafeArea(
child: Column(
children: <Widget>[
Container(
alignment: [Link],
width: 350,
height: 100,
margin: [Link](top: 40),
decoration: BoxDecoration(
borderRadius: [Link](25),
color: [Link],
),
child: Text(
"Container 1",
style: TextStyle(fontSize: 30),
),
),
Container(
alignment: [Link],
width: 350,
height: 100,
margin: [Link](top: 40),
decoration: BoxDecoration(
borderRadius: [Link](25),
color: [Link],
),
child: Text(
"Container 2",
style: TextStyle(fontSize: 30),
),
),
Container(
alignment: [Link],
width: 350,
height: 100,
margin: [Link](top: 40),
decoration: BoxDecoration(
borderRadius: [Link](25),
color: [Link],
),
child: Text(
"Container 3",
style: TextStyle(fontSize: 30),
),
),
],
),
),
),
);
}
}

Task

- remove the margins


- set height and width to 100
- give different colors
- set font size to 12
- set direction of the children:
​ “verticalDirection: [Link]/down,” - Observe that container - 1 is at the
bottom
- comment out the vertical direction
- set spacing of the children:

“mainAxisAlignment:[Link]/start/center/spaceEvenly/spaceBetween,”
- Now un-comment the vertical direction and observe the change
Note: When the vertical direction is up, the starting point for Mainaxis is from down and vice versa

- add crossAxisAlignment: [Link] - nothing changes as the size of the children is


small
So change the width of the children - only one of them and the other to align
- change the width back to 100 and create another invisible container with height 10 and width :
[Link] (occupy the space of parent) see how the other align.
- remove this container and make the crossAxisAlignment: [Link]
- add a SizedBox before each Container with height : 20 (check final code below)

import 'package:flutter/[Link]';

class AntonysApp extends StatelessWidget {


@override

Widget build(BuildContext context) {


return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
"Container example",
style: TextStyle(fontSize: 25),
)),
),
body: SafeArea(
child: Column(
//verticalDirection: [Link],
//mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
SizedBox(
height: 20,
),
Container(
width: 100,
height: 100,
alignment: [Link],
decoration: BoxDecoration(
color: [Link],
),
child: Text(
"Container 1",
style: TextStyle(fontSize: 12),
),
),
SizedBox(
height: 20,
),
Container(
width: 100,
height: 100,
alignment: [Link],
decoration: BoxDecoration(
color: [Link],
),
child: Text(
"Container 2",
style: TextStyle(fontSize: 12),
),
),
SizedBox(
height: 20,
),
Container(
width: 100,
height: 100,
alignment: [Link],
decoration: BoxDecoration(
color: [Link],
),
child: Text(
"Container 3",
style: TextStyle(fontSize: 12),
),
),
],
),
),
),
);
}
}

Now Change the Columns to rows and see the changes and play around with different values

Task: create the below


Creating a Card layout

- remove containers & everything except a child in SafeArea and Column()


- add children and <Widget>[]
- inside [] add CircleAvatar
- set radius : 50,
- set backgroundImage: AssetImage("images/[Link]"),
- after the CircleAvatar closing bracket <enter> and add Text(“Antony”)
-set style
Text(
"Antony",
style: TextStyle(
fontSize: 30,
color: [Link],
fontWeight: [Link],
)

- download a new image and change the name in [Link]


- create a new directory called ‘fonts’ under the project
- go to “[Link]” -> click on browse fonts or enter a name and search
- click on the required font and click download
- open the folder after download and drag the files to directory ‘fonts’
- update in [Link]
flutter:
uses-material-design: true
assets:
- images/robert_downey.PNG

fonts:
- family: PatrickHand
fonts:
- asset: fonts/[Link]
- press stop button and reload again for all files to get linked in, so here is one place reload will not
work
-copy the Text part down and change text to “FLUTTER DEVELOPER”
-download new font and change the font for “FLUTTER DEVELOPER”
- set the color shade “color: [Link].shade400,”
- set letterSpacing: 2
- collapse both Texts
- add a Container, add a child : Row()
- add children: <Widget>[]
- add Icon(icon)
- visit: “[Link]” check all the names of the icons
- Icon() <-- give an icon name here “smartphone”
- add a sizedbox of width 10 between Icon and Text
- add a margin for the Container with (Edgeinset) 20 for left & right
- add padding for container 10
- add color to Container “color: [Link]”
- remove the appbar

import 'package:flutter/[Link]';

class AntonysApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
backgroundColor: [Link],
body: SafeArea(
child: Column(
children: <Widget>[
CircleAvatar(
radius: 50,
backgroundImage: AssetImage("images/robert_downey.PNG"),
),
Text(
"Robert Downey Jr.",
style: TextStyle(
fontFamily: 'PatrickHand',
fontSize: 30,
color: [Link].shade900,
fontWeight: [Link],
),
),
Text(
"FLUTTER DEVELOPER",
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 22,
color: [Link].shade900,
fontWeight: [Link],
letterSpacing: 2),
),
Container(
margin: [Link](20, 0, 20, 0),
color: [Link],
padding: [Link](left: 10),
child: Row(
children: <Widget>[
Icon(
[Link],
color: [Link].shade900,
size: 40,
),
SizedBox(
width: 10,
),
Text(
"+91 12345 67890",
style: TextStyle(
color: [Link].shade900,
fontFamily: 'SourceSansPro',
fontSize: 20,
fontWeight: [Link]),
),
],
),
)
],
),
),
),
);
}
}

Adding background image in whole​



import 'package:flutter/[Link]';​

void main() {​
runApp(AntonysApp());​
}​

class AntonysApp extends StatelessWidget {​
@override​
Widget build(BuildContext context) {​
return MaterialApp(​
title: 'Scope learning app',​
home: Container(​
decoration: BoxDecoration(​
image: DecorationImage(​
image: NetworkImage(​
'[Link]
),​
fit: [Link]​
)​
),​
child:Scaffold(​
backgroundColor: [Link],​
appBar: AppBar(​
backgroundColor: [Link],​
title: Center(​
child: Text(​
"Profile Page",​
style: TextStyle(fontSize: 25),​
)),​
),​
body: SafeArea(​
child:Column(​
children: [​
SizedBox(​
height: 40,​
),​
Center(​
child: CircleAvatar(​
backgroundImage: NetworkImage(​

"[Link]
,​
// foregroundImage:
NetworkImage("[Link]
[Link]"),​
radius: 70,​
)),​
Container(​
padding: [Link](top: 20),​
child:Text("Athira",style: TextStyle(fontSize: 25,fontWeight:
FontWeight.w500),)),​
Container(​
padding: [Link](top: 20),​
child:Text("28",style: TextStyle(fontSize: 25,fontWeight:
FontWeight.w500),)),​
],​
),​
),​
),​
));​
}​
}

Adding Icons to the App in the phone


- Click home button, and drag up the screen to see all the app widgets and we will see our new App
Icon which will show flutter icon
- Download an icon you like and save it on desktop, try [Link]
- go to “[Link]”
- drag and drop the image into the place mentioned, select the required platform from right side, click
generate icon.
- it will generate a folder, go inside the folder and see the files.​
- go to andriod > click app > src > main > res,
- right click on ‘res’ and select ‘open in’ -> ‘explorer’
- click on ‘res’ again, it will show all existing mipmap files, delete the ‘mipmap’ files and drag the
downloaded files here.
- Stop and restart the app, press home button, and drag up the screen to see all the app widgets and
we will see our new App Icon.

Stateful widgets

Start with the below code:

[Link]
import 'package:my_app/widgets/[Link]';

void main() {
return runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text("click and change"),
backgroundColor: [Link],
),
body: ChangePage(),
),
));
}

class ChangePage extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return Container();
}
}

Change the code:

- change ‘Container’ to Row, add children,


- add 6 images of actors in ‘images’ folder - let the size of image be big.
- add the same in [Link], but this time let it be ‘- images/’ only
- add <Widget>[children: <Widget>[Image(image: AssetImage('images/robert_downey.PNG'))],
- wrap image with a widget, name ‘Expanded’ widget
- collapse ‘Expanded’ and copy it down 6 times and change images, see how the expanded widget
adjusts its size
- remove 3 of them, Inside ‘Expanded’ add ‘flex: 3’ before ‘child:’ in the first widget, ‘flex: 2’ in the
second widget ‘& flex: 1’ in the other - reload and check the effect

class ChangePage extends StatelessWidget {


const ChangePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(flex: 3, child: Image(image: AssetImage('images/[Link]'))),
Expanded(flex: 2, child: Image(image: AssetImage('images/[Link]'))),
Expanded(flex: 1, child: Image(image: AssetImage('images/[Link]'))),
],
);
}
}
- remove all images except one
- with only one image flex has no effect, so remove flex
Expanded(child: Image(image: AssetImage('images/[Link]'))),

Modified Code as below, and follow with the task after the code

import 'package:flutter/[Link]';

void main() {
return runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text("click and change"),
backgroundColor: [Link],
),
body: ChangePage(),
),
));
}

class ChangePage extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
var i = 2;
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const [Link](8.0),
child: TextButton(
onPressed: () {
print("button pressed");
},
child: [Link]('images/image$[Link]'),
),
)),
],
);
}
}

- remove all expanded except one


- now click on image and add padding. Default is 8 - change it 16
- click on ‘[Link]’ and wrap it with Widget and change its name to TextButton
- type onPressed: () {} ​ - I.e. onPressed is calling an anonymous function
- Inside the function - print("buton pressed");
- declare a var I inside the build
- change image names to i from existing name (img1,img2,img3)
- change code for asset to child: [Link]('images/image$[Link]'),
- click on statelesswidget and change to statefull
- change onPressed to

Task: You have 5 images in images folder, and on pressing the button we are able to print “button
presses”. Write a code inside Onpressed() so that on each button press, a different image will be
displayed.

Final Code as below

import 'package:flutter/[Link]';

void main() {
return runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text("click and change"),
backgroundColor: [Link],
),
body: ChangePage(),
),
));
}
class ChangePage extends StatefulWidget {
@override
_ChangePageState createState() => _ChangePageState();
}

class _ChangePageState extends State<ChangePage> {


int i = 1;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
child: Padding(
padding: [Link](8.0),
child: TextButton(
onPressed: () {
setState(() {
if (i < 4) {
i++;
} else {
i = 1;
}
});
},
child: [Link]('images/i$[Link]'),
),
),
),
],
);
}
}

How to use Random()

The below code will print random values and the range is given in the comments
import 'dart:math';

void main() {
var random = Random();
print([Link](75)); // number between 0 - 75
print([Link]()); // double value 0.0 to 1.0
}

Use this method to create random values to display the pictures in the earlier program

- firstly import 'dart:math';


- declare ‘var random = Random();’
- take out the if..else statement
- type in ‘i = [Link](3) + 1;’ ​ - here the ‘+1’ to avoid zero
Task

Create another box next to the existing one and make it change pictures, use the existing
picutres but use different variables to change the picture images: ​
- Copy the ‘Expanded’ block,
- press <enter> after ‘children: <Widget>[‘
- paste here.
- Add new ‘int j = 1’
- change ‘j = [Link](3) + 1;’
- change ‘child: [Link]('images/i$[Link]'),’

1.​ Now get both the pictures to change on clicking either of the images - but should
display different images
- add this in each block
​ ‘j = [Link](3) + 1;
i = [Link](3) + 1;’

2.​ Since code is repetitve, put it inside a function and remove the repetitive code, Final
code as below:-

import 'package:flutter/[Link]';
import 'dart:math';

void main() {
return runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text("click and change"),
backgroundColor: [Link],
),
body: ChangePage(),
),
));
}

class ChangePage extends StatefulWidget {


@override
_ChangePageState createState() => _ChangePageState();
}

class _ChangePageState extends State<ChangePage> {


var random = Random();
int i = 1;
int j = 1;
void face_change() {
setState(() {
i = [Link](3) + 1;
j = [Link](3) + 1;
});
}

@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: TextButton(
onPressed: () {
face_change();
},
child: [Link]('images/i$[Link]'),
)),
Expanded(
flex: 1,
child: TextButton(
onPressed: () {
face_change();
},
child: [Link]('images/i$[Link]'),
)),
],
);
}
}

ListView

ListView is a commonly used scrolling widget. It displays its children one after another in the scroll
direction.

Create the below code and

import 'package:flutter/[Link]';
import 'dart:math';

void main() {
return runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text("click and change"),
backgroundColor: [Link],
),
body: ListViewApp(),
),
));
}
class ListViewApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: ListView(
children: <Widget>[
Container(
height: 100,
child: Center(child: Text("One")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
)
],
),
),
),
);
}
}

- now copy the containers and make a total of 7 containers

Add scrolldirection:

body: SafeArea(
child: ListView(
scrollDirection: [Link],
children: <Widget> [
Container(

Note: if scrollDirection is Vertical, only height matters, width does not have any impact
Note: if scrollDirection is Horizontal, only width matters, height does not have any impact

Final code

- Every container is red, change color for each container


import 'package:flutter/[Link]';

void main() {
runApp(ListViewApp());
}

class ListViewApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: ListView(
scrollDirection: [Link],
children: [
Container(
height: 100,
child: Center(child: Text("One")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("two")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("three")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("four")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("five")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("six")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("Seven")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
],
),
),
),
);
}
}

- Have you changed color for each container

Grid View

body: SafeArea(
child: [Link](
scrollDirection: [Link],
crossAxisCount: 3 // make this 1 to get listView effect
children: <Widget>[

Note: the width and height has no consequence here as the size will depend on the no. of grids you
specify in a screen, if it is one - it will occupy the whole screen

By default the ‘scrollDirection’ is [Link], which means if crossAxisCount is 2, it will display 2 grids
horizontally and allowing to scroll downwards(vertically). If you change “scrollDirection” to
‘horizontal’, it will display 2 grids vertically and allow to scroll horizontally.
Final code

void main() {
runApp(GridViewApp());
}

class GridViewApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: [Link](
scrollDirection: [Link],
crossAxisCount: 2,
children: [
Container(
// height: 20,
// width: 30,
child: Center(child: Text("One")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("two")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("three")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("four")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("five")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("six")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("Seven")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
Container(
height: 100,
child: Center(child: Text("Eight")),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
),
],
),
),
),
);
}
}

​ --------****************---------

Using function to build containers

Roll back to listview


- create a function just after the class definition:
​ As highlighted below
- call the function inside children <Widget[

Final code

import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

void main() {
runApp(BuildContainer());
}

class BuildContainer extends StatelessWidget {


Container build_cont(Color c) {
return Container(
height: 100,
child: Center(child: Text("One")),
decoration: BoxDecoration(
color: c,
border: [Link](
color: [Link],
width: 5,
)),
);
}

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scope learning app',
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Container example")),
),
body: SafeArea(
child: ListView(
scrollDirection: [Link],
children: <Widget>[
build_cont([Link]),
build_cont([Link]),
build_cont([Link]),
build_cont([Link]),
build_cont([Link]),
build_cont([Link]),
build_cont([Link]),
],
),
),
),
);
}
}

Take out / comment out border all & simultaneously change ScrollDirection:

class ListViewApp extends StatelessWidget {


Container build_cont(Color color) {
return Container(
height: 100,
width: 100,
child: Center(child: Text("One")),
decoration: BoxDecoration(
color: color,
// border: [Link](
// color: [Link],
// width: 5,
), //),
);
}

change ScrollDirection

body: SafeArea(
child: ListView(
scrollDirection: [Link],
// crossAxisCount: 2,
children: <Widget>[
build_cont([Link]),

Change to GridView

body: SafeArea(
child: ListView(
scrollDirection: [Link],
// crossAxisCount: 2,
children: <Widget>[
build_cont([Link]),

ListViewBuilder
[Link] is a way of constructing the list where children’s (Widgets) are built on demand.

using [Link]()

[Link](n, (i) => “Item”)

will create a list with ‘n’ no. of ‘items’ and you can manipulate each item through the arrow function
that takes ‘i’ as an index for elements in the list. We can use this function to create a list.

Example 1

import 'package:flutter/[Link]';

final myList = List<String>.generate(100, (i) => 'List Item ${i + 1}');

void main() {
print(myList);
runApp(ListViewBuilder());
}

class ListViewBuilder extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Listview builder',
home: BuilderPage(),
);
}
}

class BuilderPage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List view builder using "[Link]"'),
),
body: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
child: Padding(
padding: const [Link](25),
child: Text(myList[index])),
);
}));
}
}

Example2

import 'package:flutter/[Link]';
List<String> myList = [
"Antony",
"Jibin",
"Shiffin",
"Ashik",
"Arya",
"Vishnu",
"Fawas",
"Rahul",
"Koshy",
"Riya",
"Roopa"
];
void main() {
print(myList);
runApp(ListViewBuilder());
}

class ListViewBuilder extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Listview builder',
home: BuilderPage(),
);
}
}

class BuilderPage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List view builder'),
),
body: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
child: Padding(
padding: const [Link](25),
child: Text(myList[index])),
);
}));
}
}

Expanded Widget

Expanded widget comes in handy when we want a child widget or children widgets to take all the
available space along the main-axis (for Row the main axis is horizontal & vertical for Column).
Expanded widget can be taken as the child of Row, Column, and Flex. And in case if we don’t want to
give equal spaces to our children widgets we can distribute the available space as our will using flex
factor.

Constructor of Expanded class:


const Expanded(
{Key? key,
int flex: 1,
required Widget child}
)

Properties of Expanded Widget:

child: This property sets the widget tree to be placed inside the Expanded widget. Expanded widget
can be taken as the child of Row, Column, and Flex.

fit: This property controls how the child widget fills the available space. There are two options given by
flutter, the first is
- [Link] which sets the child to fill the space available to it and the second is
- [Link] which allows the child widget to be as large as the available space.

flex: If we decide to distribute the available space unevenly among the widgets, then we use the flex
to do the same.

Example 1: In this example, Expanded widget is used inside a Column:

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text('Expanded Widget')),
backgroundColor: [Link][400],
),
body: Center(
child: Column(
children: <Widget>[
Container(
child: Center(
child: Text(
'First widget',
style: TextStyle(
color: [Link],
),
),
),
color: [Link],
height: 100,
width: 200,
),
Expanded(
child: Container(
child: Center(
child: Text(
'Second widget',
style: TextStyle(
color: [Link],
),
),
),
color: [Link],
width: 200,
),
),
Container(
child: Center(
child: Text(
'Third widget',
style: TextStyle(
color: [Link],
),
),
),
color: [Link],
height: 100,
width: 200,
),
],
)),
),
debugShowCheckedModeBanner: false,
));
}

- Now remove ‘Expanded’ from the 2nd container and see the difference.
- Now add back the ‘Expanded’ and change ‘Column’ to ‘row’ and see
- Mention height and width for the 2nd container
width: 200,
​ height: 100, (nothing changes)

- Remove ‘Center’ from ‘body’ of ‘Scaffold’ and see


- Change ‘Column’ to ‘Row’ and see
- change the size of other containers and see how expanded changes its size

Cards

A card is a sheet used to represent the information related to each other, such as an album, a
geographical location, contact details, etc. We mainly use it to store the content and action of a single
object.

Eg:-
import 'package:flutter/[Link]';

void main() => runApp(CardApp());

class CardApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(

appBar: AppBar(
title: Center(child: Text('Flutter Card Example')),
backgroundColor: [Link],
),
backgroundColor: [Link],
body: CardShapes(),
),
);
}
}
class CardShapes extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: [Link],
width: 3,
),
borderRadius: [Link](20.0),
),
child: Container(
padding: [Link](16),
child: Text(
'RoundedRectangleBorder',
style: TextStyle(fontSize: 25, fontWeight: [Link]),
),
),
),
Card(
shape: BeveledRectangleBorder(
side: BorderSide(
color: [Link],
width: 3,
),
borderRadius: [Link](20.0),
),
child: Container(
padding: [Link](16),
child: Text(
'BeveledRectangleBorder',
style: TextStyle(fontSize: 25, fontWeight: [Link]),
),
),
),
Card(
shape: StadiumBorder(
side: BorderSide(
color: [Link],
width: 2.0,
),
),
child: Container(
padding: [Link](16),
child: Text(
'StadiumBorder',
style: TextStyle(fontSize: 25, fontWeight: [Link]),
),
),
),
],
));
}
}

ListTile Widget
Stateful with setState()

ListTile widget is used to populate a ListView in Flutter, it contains title as well as leading or trailing
icons.

The below creates a stateful widget which calls setstate() method on detecting onTap: ()

import 'package:flutter/[Link]';
void main() {
runApp(ListTileApp());
}

class ListTileApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListTile',
theme: ThemeData(
primarySwatch: [Link],
),
home: ListPage(),
debugShowCheckedModeBanner: false,
);
}
}
class ListPage extends StatefulWidget {
@override
_ListPageState createState() => _ListPageState();
}
class _ListPageState extends State<ListPage> {
String txt = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List tile example'),
backgroundColor: [Link],
),
backgroundColor: [Link][100],
body: Column(
children: <Widget>[
Padding(
padding: [Link](8.0),
child: Container(
color: [Link][50],
child: ListTile(
leading: Icon([Link]),
title: Text(
'List Item 1',
textScaleFactor: 1.5,
),
trailing: Icon([Link]),
subtitle: Text('This is subtitle'),
selected: true,
onTap: () {
setState(() {
txt = 'List Tile pressed';
});
},
),
),
),
Text(
txt,
textScaleFactor: 2,
)
],
),
);
}
}
Where() method: This is a list method that takes a function as a parameter and returns the result of
a test condition

void main() {
// Find all names that has letter a
List<String> students = ['Max', 'John', 'Sara', 'Peter'];
Iterable<String> names = [Link](
(name) => [Link]('a'),
);
print(names);

//Find all even numbers


List<int> numbers = [13, 2890, 95234, 79357, 300];
Iterable<int> evenNumbers = [Link](
(num) => (num % 2 == 0),
);
print(evenNumbers);

//Find all german friends


List<Student> allStudents = [
Student(name: 'David', state: 'Kerala'),
Student(name: 'Max', state: 'Mumbai'),
Student(name: 'Sara', state: 'Kerala'),
Student(name: 'Daniel', state: 'Delhi')
];

Iterable<Student> keralaStudents = [Link](


(friend) => [Link]('Kerala'),
);
[Link](
(friend) => print([Link]),
);
}

class Student {
String name;
String state;
Student({required [Link], required [Link]});
}

What is an Iterable?

An Iterable is a collection of elements that can be accessed sequentially. In Dart, an Iterable is an


abstract class, meaning that you can’t instantiate it directly. However, you can create a new Iterable by
creating a new List or Set. Both List and Set are Iterable, so they have the same methods and
properties as the Iterable class where as Map is different.

Eg:-

Iterable<int> iterable = [1, 2, 3];

Iterable, as opposed to List, doesn’t have the [] operator.


following code, which is invalid:

Iterable<int> iterable = [1, 2, 3];


int value = iterable[1];

Instead use

void main() {
Iterable<int> it = [1, 2, 3];
int i = [Link](1);
print(i);
}

Using a ‘for -in’ loop

void main() {
Iterable<String> iterable = ['Salad', 'Popcorn', 'Toast'];
for (String element in iterable) {
print(element);
}
}

void main() {
Iterable<int> ite = [10, 30, 20, 50, 40];
for (int i in ite) {
print(i);
}
}

Revisiting the ListviewBuilder with The SearchApp

We are using the following in this app:


1.​ Expanded()
2.​ Card()
3.​ Listtile()
4.​ initState()
5.​ setState()
6.​ where()

import 'package:flutter/[Link]';

void main() {
runApp(SearchListApp());
}

class SearchListApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Search List',
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


final List<Map<String, dynamic>> persons = [
{"id": 1, "name": "Antony", "age": 45},
{"id": 2, "name": "Arathy", "age": 40},
{"id": 3, "name": "Shiffin", "age": 25},
{"id": 4, "name": "Koshy", "age": 35},
{"id": 5, "name": "Ashik", "age": 21},
{"id": 6, "name": "Arya", "age": 55},
{"id": 7, "name": "Jibin", "age": 30},
{"id": 8, "name": "Janaky", "age": 14},
{"id": 9, "name": "Febin", "age": 30},
{"id": 10, "name": "Rahul", "age": 18},
];

List<Map<String, dynamic>> _foundPersons = [];


@override
initState() {
// at the beginning, all users are shown
_foundPersons = persons;
[Link]();
}

// This function is called whenever the text field changes


void _filter(String searchKey) {
List<Map<String, dynamic>> results = [];
if ([Link]) {
// if the search field is empty or only contains white-space, we'll display all users
results = persons;
} else {
results = persons
.where((person) => person["name"]
.toLowerCase()
.contains([Link]()))
.toList();
// we use the toLowerCase() method to make it case-insensitive
}

// Refresh the UI
setState(() {
_foundPersons = results;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text('List Search App')),
),
body: Padding(
padding: [Link](10),
child: Column(
children: [
SizedBox(
height: 20,
),
TextField(
onChanged: (value) => _filter(value),
decoration: InputDecoration(
labelText: 'Search', suffixIcon: Icon([Link])),
),
SizedBox(
height: 20,
),
Expanded(
child: _foundPersons.isNotEmpty
? [Link](
itemCount: _foundPersons.length,
itemBuilder: (context, index) => Card(
key: ValueKey(_foundPersons[index]["id"]),
color: [Link],
margin: [Link](vertical: 8),
child: ListTile(
leading: Text(
_foundPersons[index]["id"].toString(),
style: TextStyle(fontSize: 24),
),
title: Text(_foundPersons[index]['name']),
subtitle: Text(
'${_foundPersons[index]["age"].toString()} years old'),
),
),
)
: Text(
'No results found',
style: TextStyle(fontSize: 24),
),
),
],
),
),
);
}
}

Inkwell

InkWell is a rectangular area of a material in Flutter that responds to touch in an application. The
InkWell widget must have a material widget as its ancestor. The material widget is where the ink
reactions are actually performed. InkWell reactions respond when the user clicks the button.

import 'package:flutter/[Link]';

void main() {
runApp(InkwellApp());
}

class InkwellApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'InkWell App',
theme: ThemeData(
primarySwatch: [Link],
),
home: InkwellPage(),
debugShowCheckedModeBanner: false,
);
}
}

class InkwellPage extends StatefulWidget {


@override
_InkwellPageState createState() => _InkwellPageState();
}

class _InkwellPageState extends State<InkwellPage> {


String message = 'this will change';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('InkWell Widget'),
backgroundColor: [Link].shade400,
// actions: <Widget>[Text('Tap or Press')],
),
backgroundColor: [Link][50],
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: <Widget>[
InkWell(
onTap: () {
setState(() {
message = 'Inkwell Tapped';
});
},
onLongPress: () {
setState(() {
message = 'InkWell Long Pressed';
});
},
child: Container(
color: [Link].shade400,
width: 120,
height: 70,
child: Center(
child: Text(
'Touch here',
textScaleFactor: 1.5,
style: TextStyle(fontWeight: [Link]),
))),
),
Text(
message,
textScaleFactor: 2,
)
],
),
),
);
}
}

Pageview

A scrollable list that works page by page. Each child of a page view is forced to be the same size as the
viewport. scrollDirection can be changed to scroll horizontally or vertically.

Eg:-

import 'package:flutter/[Link]';

void main() {
runApp(PageViewApp());
}

class PageViewApp extends StatelessWidget {


static String _title = 'PageView App';
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: _title,
home: PageViewPage(),
);
}
}

class PageViewPage extends StatelessWidget {


PageViewPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text('PageView Widget')),
),
body: PageView(
scrollDirection: [Link],
children: <Widget>[
Container(
color: [Link],
child: Text(
'Page One',
style: TextStyle(
fontFamily: 'Courier',
fontSize: 25,
fontWeight: [Link],
),
),
),
Container(
color: [Link],
child: Text(
'Page Two',
style: TextStyle(
fontFamily: 'Courier',
fontSize: 25,
fontWeight: [Link],
),
),
),
Container(
color: [Link],
child: Text(
'Page Three',
style: TextStyle(
fontFamily: 'Courier',
fontSize: 25,
fontWeight: [Link],
),
),
),
],
),
);
}
}

Using PageView to build pages dynamically

import 'package:flutter/[Link]';

int _curr = 0;

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

class MyApp extends StatelessWidget {


// This widget is the root
// of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PageView dynamic',
theme: ThemeData(
primarySwatch: [Link],
),
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {


@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


PageController controller = PageController();
List<Widget> _pages = <Widget>[
new Center(
child: new Pages(
text: "Existing Page",
))
];

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Center(child: Text("PageBuilder")),
backgroundColor: [Link],
actions: <Widget>[
Padding(
padding: const [Link](3.0),
child: Text(
"Page: " +
(_curr + 1).toString() +
"/" +
_pages.[Link](),
textScaleFactor: 2,
),
)
],
),
body: PageView(
children: _pages,
scrollDirection: [Link],

// reverse: true,
// physics: BouncingScrollPhysics(),
controller: controller,
onPageChanged: (num) {
setState(() {
_curr = num;
});
},
),
floatingActionButton: Row(
mainAxisAlignment: [Link],
children: <Widget>[
FloatingActionButton(
onPressed: () {
setState(() {
_pages.add(
new Center(
child: new Text("Added Page",
style: new TextStyle(fontSize: 35.0))),
);
});
if (_curr != _pages.length - 1)
[Link](_curr + 1);
else
[Link](0);
},
child: Icon([Link])),
FloatingActionButton(
onPressed: () {
_pages.removeAt(_curr);
setState(() {
[Link](_curr - 1);
});
},
child: Icon([Link])),
]));
}
}

class Pages extends StatelessWidget {


final text;
Pages({[Link]});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: [Link],
children: <Widget>[
Text(
text,
textAlign: [Link],
style: TextStyle(fontSize: 30, fontWeight: [Link]),
),
]),
);
}
}

PageViewBuilder

Creates a scrollable list that works page by page using widgets that are created on demand. It is
appropriate for page views with a large (or infinite) number of children because the builder is called
only for those children that are actually visible. Providing a non-null itemCount lets the PageView
compute the maximum scroll extent.

itemBuilder will be called only with indices greater than or equal to zero and less than itemCount.

A few other key information about [Link] constructor.

Firstly, by default, [Link] doesn’t support child reordering. We can either use PageView or
[Link] constructor to do that.

Secondly, [Link] doesn’t allow null value for the allowImplicitScrolling parameter.

Since [Link] is a constructor of PageView, which has StatefulWidget as its immediate


ancestor, therefore, [Link] effects are not going to work with Stateless widget. Although we
can always experiment with the Provider package.
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PageBuilder',
theme: ThemeData(
primarySwatch: [Link],
),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("PageViewBuilder Demo"),
),
),
body: [Link](
itemCount: 10,
itemBuilder: (context, position) {
Color color;
if (position % 3 == 0) {
color = [Link];
} else if (position % 3 == 1) {
color = [Link];
} else {
color = [Link];
}
return Container(
color: color,
child: Center(child: Text("Page No: ${position}")),
);
},
),
));
}
}

An itemBuilder attribute holds the space to create the actual page. The itemCount, on the other hand,
is used to create the pages given a number of times. If the itemCount is empty, infinite pages are
constructed.

Below eg will create an infite no of pages:-

body: [Link](
// itemCount: 10,
itemBuilder: (context, position) {
Color color;

MediaQuery
Size:

import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(home: MQApp()));
}
class MQApp extends StatelessWidget {
var size, height, width;

@override
Widget build(BuildContext context) {
// getting the size of the window
size = [Link](context).size;
height = [Link];
width = [Link];
return Scaffold(
appBar: AppBar(
title: Text("Media Query example"),
backgroundColor: [Link],
),
body: Container(
color: [Link],
height: height / 4, //half of the height size
width: width / 4, //half of the width size
),
);
}
}

Orientation:

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(home: MQOrientationApp()));
}

class MQOrientationApp extends StatelessWidget {


var orientation, size, height, width;

@override
Widget build(BuildContext context) {
// getting the orientation of the app
orientation = [Link](context).orientation;

//size of the window


size = [Link](context).size;
height = [Link];
width = [Link];

return Scaffold(
appBar: AppBar(
title: Text("MQ orientation"),
backgroundColor: [Link],
),
// checking the orientation
body: orientation == [Link]
? Container(
color: [Link],
height: height / 4,
width: width / 4,
)
: Container(
height: height / 3,
width: width / 3,
color: [Link],
),
);
}
}

Buttons

o​ Text Button
o​ Elevated Button
o​ Floating Action Button
o​ Drop Down Button
o​ Icon Button
o​ PopupMenu Button
o​ Outline Button

Example of all the above buttons:-

import 'package:flutter/[Link]';

var message = "no button";


var items = [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
];

String dropdownvalue = 'Item 1';


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

class MyApp extends StatefulWidget {


@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
title: Text('Flutter Button Widgets'),
),
body: Center(
child: Column(children: <Widget>[
SizedBox(
height: 20,
),
Container(
// margin: [Link](25),
child: TextButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text(
'TextButton',
style: TextStyle(fontSize: 20.0, color: [Link]),
),
onPressed: () {
setState(() {
message = "Text Button";
});
},
),
),
Container(
// margin: [Link](25),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: [Link]([Link])),
child: Text(
'Elevated Button',
style: TextStyle(fontSize: 20.0),
),
onPressed: () {
setState(() {
message = "Elevated Button";
});
},
),
),
Container(
margin: [Link](25),
child: FloatingActionButton(
child: Icon([Link]),
backgroundColor: [Link].shade700,
onPressed: () {
setState(() {
message = "Floating Action Button";
});
},
),
),
Container(
child: DropdownButton(
// Initial Value
value: dropdownvalue,

// Down Arrow Icon


icon: const Icon(Icons.keyboard_arrow_down),

// Array list of items


items: [Link]((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
onChanged: (String? value) {
setState(() {
dropdownvalue = value!;
message = "${value} from drop down";
});
},
// After selecting the desired option,it will
// change button value to selected value
),
),
Container(
padding: [Link](50),
alignment: [Link],
child: IconButton(
icon: Icon(
Icons.directions_transit,
),
iconSize: 50,
color: [Link],
splashColor: [Link],
onPressed: () {
setState(() {
message = "Icon Button";
});
},
),
),
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(
child: Text("First"),
value: 1,
),
PopupMenuItem(
child: Text("Second"),
value: 2,
)
],
onSelected: (value) {
setState(() {
message = "Popup${value}";
});
},
),
Center(
child: OutlinedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Outline Button'),
onPressed: () {
setState(() {
message = "Outlined Button";
});
},
),
),
Container(
child: Center(
child: Text(
"You clicked:${message}",
style: TextStyle(
color: [Link],
fontSize: 20,
fontWeight: [Link]),
),
),
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
width: 5,
),
),
),
]))),
);
}
}

A custom ElevatedButton with child assigned a function to create a widget to show row with separate
contents

import 'package:flutter/[Link]';

class ButtonWidget extends StatelessWidget {


final IconData icon;
final String text;
final VoidCallback onClicked;

const ButtonWidget({
Key? key,
required [Link],
required [Link],
required [Link],
}) : super(key: key);

@override
Widget build(BuildContext context) => ElevatedButton(
style: [Link](
backgroundColor: [Link].shade900,
minimumSize: [Link](50),
),
child: buildContent(),
onPressed: onClicked,
);

Widget buildContent() => Row(


mainAxisSize: [Link],
children: [
Icon(icon, size: 28),
SizedBox(width: 16),
Text(
text,
style: TextStyle(
fontSize: 22,
color: [Link],
),
),
],
);
}

GestureDetector

import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: GestureDetectorScreen(),
));
}

class GestureDetectorScreen extends StatefulWidget {


@override
_GestureDetectorScreenState createState() => _GestureDetectorScreenState();
}

class _GestureDetectorScreenState extends State<GestureDetectorScreen> {


Color cl = [Link];
Text txt = Text(
"Hello! it's Teal Color",
style: TextStyle(fontSize: 18, fontWeight: [Link]),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
centerTitle: true,
title: Text('Gesture Detector Demo'),
),
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
cl = [Link];
txt = Text(
"Tap detected",
style: TextStyle(fontSize: 18, fontWeight: [Link]),
);
});
},
onDoubleTap: () {
setState(() {
cl = [Link];
txt = Text(
"double tap detected",
style: TextStyle(
fontSize: 18,
fontWeight: [Link],
color: [Link]),
);
});
},
onLongPress: () {
setState(() {
cl = [Link];
txt = Text(
"Long press detected",
style: TextStyle(fontSize: 18, fontWeight: [Link]),
);
});
},
child: Container(
decoration: BoxDecoration(
color: cl, borderRadius: [Link](160)),
width: 300,
height: 300,
child: Center(
child: txt,
)),
),
),
);
}
}

SnackBar

SnackBar is a Flutter widget that enables temporary display of a pop-up message in your app, It
usually appears at the bottom of the app's screen.

import 'package:flutter/[Link]';

void main() => runApp(SnackBarApp());

class SnackBarApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Snackbar")),
body: Center(
child: MyStatelessWidget(),
),
),
);
}
}

class MyStatelessWidget extends StatelessWidget {


@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: () {
[Link](context).showSnackBar(
SnackBar(
backgroundColor: [Link],
content: Text('A SnackBar demo shown.'),
),
);
},
child: Text('Show SnackBar'),
);
}
}

Layout Builder

Builds a widget tree that depends on the size of the parent widget. The framework calls the builder
function at layout time and provides the constraints of the parent widget. This is useful when the
parent constrains the size of the child and doesn't depend on the intrinsic size of the child. The final
size of the LayoutBuilder will match the size of its child.

[Link]
Eg:1

import 'package:flutter/[Link]';
void main() => runApp(LayoutApp());
class LayoutApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'LayoutBuilder',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: [Link],
),
home: LayoutBuilderApp(),
);
}
}​
class LayoutBuilderApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Layout Widget'),
),
body: Container(
color: [Link],
height: [Link](context).[Link] * 0.75,
width: [Link](context).[Link],
alignment: [Link],
child: LayoutBuilder(
builder: (BuildContext ctx, BoxConstraints constraints) {
return Container(
color: [Link],
alignment: [Link],
height: [Link] * 0.5,
width: [Link] * 0.5,
child: Text(
'LayoutBuilder Widget',
style: TextStyle(
fontSize: 18,
fontWeight: [Link],
color: [Link],
),
),
);
},
),
),
),
);
}
}

Eg:2

import 'package:flutter/[Link]';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {


const MyApp({[Link]});

static const String _title = 'Flutter Code Sample';

@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}

class MyStatelessWidget extends StatelessWidget {


const MyStatelessWidget({[Link]});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('LayoutBuilder Example')),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if ([Link] > 411) {
return _buildWideContainers();
} else {
return _buildNormalContainer();
}
},
),
);
}

Widget _buildNormalContainer() {
return Center(
child: Container(
height: 100.0,
width: 100.0,
color: [Link],
),
);
}

Widget _buildWideContainers() {
return Center(
child: Row(
mainAxisAlignment: [Link],
children: <Widget>[
Container(
height: 100.0,
width: 100.0,
color: [Link],
),
Container(
height: 100.0,
width: 100.0,
color: [Link],
),
],
),
);
}
}

Flutter Packages

Go to [Link]/flutter -> search for ‘english_words’ -> to add this to our project,

- add the below to [Link], under ‘cupertino_icons, add:


cupertino_icons: ^1.0.2
english_words: ^4.0.0

- the ‘^’ indicates that any version above 4 but within 4 and not 5, as an upgrade to version 5 means
basic functionality change, so there is a risk of your code being broken - hence program may not
function

- in [Link] add: copy and past the import statement from the flutter package

​ import 'package:english_words/english_words. [Link]';

void main() => runApp(WordsApp());

class WordsApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(child: Text([Link])),
),
),
);
}
}

Instead of [Link], check out other options that come up after giving ‘.’.


Bottom Navigation bar

A bottom navigation bar is a widget that is present at the bottom of an app for selecting or navigating
to different pages of the app. It is usually used in conjunction with a Scaffold, where it is provided as
the Scaffold. bottomNavigationBar argument.

import 'package:flutter/[Link]';

void main() => runApp(NaviApp());

class NaviApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: BottomNavigation(),
);
}
}

class BottomNavigation extends StatefulWidget {


@override
_BottomNavigationState createState() => _BottomNavigationState();
}

class _BottomNavigationState extends State<BottomNavigation> {


int _selectedIndex = 0;
static List<Widget> _widgetOptions = <Widget>[
Text('Home Page',
style: TextStyle(fontSize: 35, fontWeight: [Link])),
Text('Search Page',
style: TextStyle(fontSize: 35, fontWeight: [Link])),
Text('Profile Page',
style: TextStyle(fontSize: 35, fontWeight: [Link])),
];

void changeIndex(int ind) {


setState(() {
print("Value of ind: ${ind}");
_selectedIndex = ind;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter BottomNavigationBar Example'),
backgroundColor: [Link]),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon([Link]), label: 'Home'),
BottomNavigationBarItem(
icon: Icon([Link]),
label: 'Search',
),
BottomNavigationBarItem(icon: Icon([Link]), label: 'Profile'),
],
type: [Link],
currentIndex: _selectedIndex,
selectedItemColor: [Link],
iconSize: 40,
onTap: changeIndex,
elevation: 5),
);
}
}

Tab Bar
A common navigation pattern on mobile is to show multiple tabs with different pages inside them.

[Link]
import 'package:flutter/[Link]';
import 'other_topics/[Link]';
import 'other_topics/[Link]';

void main() => runApp(TabBarApp());

class TabBarApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Tab bar Demo'),
bottom: TabBar(
tabs: [
Tab(icon: Icon([Link]), text: "Tab 1"),
Tab(icon: Icon(Icons.add_shopping_cart_sharp), text: "Tab 2")
],
),
),
body: TabBarView(
children: <Widget>[
Contacts(),
Cart(),
],
),
),
),
);
}
}

[Link]

import 'package:flutter/[Link]';

class Contacts extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text(
'List your Contacts here',
style: TextStyle(fontSize: 30.0),
)),
);
}
}
[Link]

import 'package:flutter/[Link]';

class Cart extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text(
'List your booked items here',
style: TextStyle(fontSize: 30.0),
),
),
);
}
}

Stacks
Stack is a widget in Flutter that contains a list of widgets and positions them on top of one another. In
other words, the stack allows developers to overlap multiple widgets into a single screen and renders
them from bottom to top. The first widget is the bottommost item, and the last widget is the topmost
item.

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: Scaffold(
backgroundColor: [Link].shade400,
appBar: AppBar(k Container(
width: 400,
height: 500,
color: [Link],
), //Container
Container(
width: 300,
height: 350,
color: [Link],-
), //Container
Container(
width: 150,
height: 200,
color: [Link],
), //Container
], //<Widget>[]
), //Stack
), //SizedBox
) //Center
) //Scaffold
) //MaterilApp
);
}

Eg2:-
import 'package:flutter/[Link]';

//import 'view/my_app.dart';

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

class NewPage extends StatelessWidget {


NewPage([Link]);
String txt;
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text(txt),
),
);
}
}

class MyApp extends StatelessWidget {


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

static const String title = 'Basic Layout';

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
home: MyAppHome(),
);
}
}

class MyAppHome extends StatelessWidget {


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

static const String userUrl =

'[Link]
oad-3133502_1920.jpg';

@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
[Link],
[Link],
],
begin: [Link],
end: [Link],
),
),
),
titleSpacing: 80,
leading: const Icon([Link]),
// title: const Text(
// 'Let\'s Go!',
// textAlign: [Link],
// ),
actions: [
buildIcons(
const Icon(Icons.add_a_photo),
),
buildIcons(
const Icon(
Icons.notification_add,
),
),
buildIcons(
const Icon(
[Link],
),
),
buildIcons(
const Icon([Link]),
),
],
bottom: const TabBar(
isScrollable: true,
indicatorColor: [Link],
indicatorWeight: 5,
tabs: [
Tab(
icon: Icon(
[Link],
),
text: 'Home',
),
Tab(
icon: Icon(
Icons.panorama_fish_eye,
),
text: 'Log in',
),
Tab(
icon: Icon(
[Link],
),
text: 'Settings',
),
Tab(
icon: Icon(
Icons.local_activity,
),
text: 'Location',
),
],
),
),
body: TabBarView(children: [
ListView(
children: [
Stack(
clipBehavior: [Link],
children: [
Container(
height: 200,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
[Link],
[Link],
],
begin: [Link],
end: [Link],
),
),
),
Positioned(
bottom: -15,
left: 0,
right: 0,
child: Center(
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
borderRadius: [Link](50),
boxShadow: const [
BoxShadow(
color: [Link],
spreadRadius: 4,
),
],
image: const DecorationImage(
fit: [Link],
image: NetworkImage(userUrl),
),
),
),
),
),
Positioned(
bottom: 25,
left: 0,
right: 0,
child: Center(
child: Container(
margin: const [Link](17),
width: 300,
height: 100,
child: const Text(
'Lorem Ipsum',
textAlign: [Link],
style: TextStyle(
fontSize: 30,
fontWeight: [Link],
),
),
),
),
),
],
),

/// coming out of Stack


///
Container(
margin: const [Link](10),
padding: const [Link](top: 75),
child: const Text(
'since its launch in 2005, the bugatti veyron has been regarded as
a supercar '
'of superlative quality. it was a real challenge for developers to
fulfill '
'the specifications that the new supercar was supposed to meet:
over 1,000 hp, '
'a top speed of over 400 km/h and the ability to accelerate from 0
to 100 in under '
'three seconds. even experts thought it was impossible to achieve
these performance '
'specs on the road. but that was not all.',
textAlign: [Link],
style: TextStyle(
fontSize: 22,
),
),
),
],
),
NewPage('Log in'),
NewPage('Settings'),
NewPage('Location'),
])),
);
}

IconButton buildIcons(Icon icon) {


return IconButton(
onPressed: () {},
icon: icon,
);
}
}

Navigating Screens(routing)

In any mobile app, navigating to different pages defines the workflow of the application, and the way
to handle the navigation is known as routing. Flutter provides a basic routing class called
“MaterialPageRoute” and two methods [Link]() and [Link]().

[Link]
import 'package:flutter/[Link]';
import '[Link]';
void main() {
runApp(MaterialApp(
title: 'Flutter Navigation',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
home: HomePage(),
));
}

class HomePage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Text('Home Page'),
),
body: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: [Link]([Link])),
child: Text('Another Page'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => AnotherPage()),
);
},
),
),
);
}
}

class AnotherPage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Text("Another Screen"),
),
body: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: [Link]([Link])),
onPressed: () {
[Link](context);
},
child: Text('Go Home'),
),
),
);
}
}

Navigation with Named Routes

import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(
title: 'Named Page Routing',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/second': (context) => SecondPage(),
'/third': (context) => ThirdPage(),
},
));
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Text('Home Page'),
),
body: Column(
children: [
SizedBox(
height: 70,
),
Center(
child: ElevatedButton(
child: Text('Second Page'),
onPressed: () {
[Link](context, '/second');
},
),
),
SizedBox(
height: 50,
),
Center(
child: ElevatedButton(
child: Text('Third Page'),
onPressed: () {
[Link](context, '/third');
},
),
),
],
),
);
}
}

class SecondPage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Text("Second Page"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
[Link](context);
},
child: Text('Back to home'),
),
),
);
}
}

class ThirdPage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Text("Third Page"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
[Link](context);
},
child: Text('Back to home'),
),
),
);
}
}

Another eg with snackbar and returning data

import 'package:flutter/[Link]';

void main() {
runApp(
const MaterialApp(
title: 'Returning Data',
home: HomeScreen(),
),
);
}

class HomeScreen extends StatelessWidget {


const HomeScreen({[Link]});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Returning Data Demo'),
),
body: const Center(
child: SelectionButton(),
),
);
}
}

class SelectionButton extends StatefulWidget {


const SelectionButton({[Link]});

@override
State<SelectionButton> createState() => _SelectionButtonState();
}

class _SelectionButtonState extends State<SelectionButton> {


@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
_navigateAndDisplaySelection(context);
},
child: const Text('Pick an option, any option!'),
);
}

// A method that launches the SelectionScreen and awaits the result from
// [Link].
Future<void> _navigateAndDisplaySelection(BuildContext context) async {
// [Link] returns a Future that completes after calling
// [Link] on the Selection Screen.
final result = await [Link](
context,
MaterialPageRoute(builder: (context) => const SelectionScreen()),
);

// When a BuildContext is used from a StatefulWidget, the mounted property


// must be checked after an asynchronous gap.
if (!mounted) return;

// After the Selection Screen returns a result, hide any previous snackbars
// and show the new result.
[Link](context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$result')));
}
}

class SelectionScreen extends StatelessWidget {


const SelectionScreen({[Link]});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Pick an option'),
),
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: <Widget>[
Padding(
padding: const [Link](8.0),
child: ElevatedButton(
onPressed: () {
// Close the screen and return "Yep!" as the result.
[Link](context, 'Yep!');
},
child: const Text('Yep!'),
),
),
Padding(
padding: const [Link](8.0),
child: ElevatedButton(
onPressed: () {
// Close the screen and return "Nope." as the result.
[Link](context, 'Nope.');
},
child: const Text('Nope.'),
),
)
],
),
),
);
}
}

Input Fields in Flutter

TextField: This is the most basic Flutter widget for getting text input from a user.

TextFormField: If you find yourself needing to validate user text input before you save it, you might
consider using a TextFormField.

Though you could still just use a couple of TextFields and validate it, TextFormField has extra builtin
functionality for easier validation. TextFormField is usually inside Form widget (though that isn't a
strict requirement).

TextField
Eg:-
import 'package:flutter/[Link]';

String firstName = "";


String surName = "";
String userName = "";
String password = "";
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}

class _State extends State<MyApp> {


@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false, //change to false to keep screen in tact
appBar: AppBar(
title: Text('Flutter TextField Example'),
),
body: Padding(
padding: [Link](15),
child: Column(
children: <Widget>[
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
firstName = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'First Name',
hintText: 'Enter First Name',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
surName = i;
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Sur Name',
hintText: 'Enter Sur Name',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
userName = i;-
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'User Name',
hintText: 'Enter Your Name',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
password = i;
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
),
),
),
ElevatedButton(
child: Text('Sign In'),
onPressed: () {
print(userName);
print(password);
},
)
],
)));
}
}

resizeToAvoidBottomInset

resizeToAvoidBottomInset: if there is an onscreen keyboard displayed, the body can be resized to


avoid overlapping the keyboard, which prevents widgets inside the body from being obscured by the
keyboard. Defaults to true, but sometimes we may need to turn this to false to avoid screen from
breaking. This is a property of Scaffold().

Task1: Create another or same screen and display both the entered values on clicking the sign in
button.

Task2: Create a page to enter registration details and display it on same screen
Name:
Date of Birth:
City:
Phone No:
Login ID:
Password:
A button to [register].
On clicking the button display the details in the screen

Color Codes in Flutter

Quizapp

[Link]
import 'package:flutter/[Link]';
import 'package:quizapp/[Link]';
import 'package:rflutter_alert/rflutter_alert.dart';

QuizManager qManager = QuizManager();

void main() {
runApp(QuizApp());
}

class QuizApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Personal Demo Quiz"),
),
backgroundColor: [Link],
),
backgroundColor: [Link].shade900,
body: SafeArea(
child: Padding(
padding: [Link](horizontal: 10.0),
child: QuizPage(),
),
),
),
);
}
}

class QuizPage extends StatefulWidget {


@override
_QuizPageState createState() => _QuizPageState();
}

class _QuizPageState extends State<QuizPage> {


List<Widget> scoreKeeper = [];
void checkAnswer(bool userAnswer) {
setState(() {
if ([Link]() == true) {
Alert(
context: context,
title: 'Finished!',
desc: 'You have reached the end of the quiz.',
).show();
[Link]();
scoreKeeper = [];
} else {
if ([Link]() == userAnswer) {
[Link](Icon(
[Link],
color: [Link],
));
} else {
[Link](Icon(
[Link],
color: [Link],
));
}
[Link]();
}
});
}

@override build
Widget (BuildContext context) {
return Column(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
Expanded(
flex: 5,
child: Padding(
padding: [Link](10.0),
child: Center(
child: Text(
[Link](),
textAlign: [Link],
style: TextStyle(
fontSize: 25.0,
color: [Link],
),
),
),
),
),
Expanded(
child: Padding(
padding: [Link](15.0),
child: TextButton(
style: ButtonStyle(
backgroundColor: [Link]([Link])),
child: Text(
"True",
style: TextStyle(
color: [Link],
fontSize: 20.0,
),
),
onPressed: () {
//The user picked True
checkAnswer(true);
},
),
),
),
Expanded(
child: Padding(
padding: [Link](15.0),
child: TextButton(
style: ButtonStyle(
backgroundColor: [Link]([Link])),
child: Text(
"False",
style: TextStyle(
color: [Link],
fontSize: 20.0,
),
),
onPressed: () {
//The user picked false
checkAnswer(false);
},
),
),
),
Row(
children: scoreKeeper,
),
],
);
}
}

[Link]

import '[Link]';
class QuizManager {
int _qno = 0;
List<Question> _questionBank = [
Question("I am a good person", true),
Question('Everybody likes me and I like everybody', false),
Question('I take accountability for my actions', true),
Question('Life is always smooth', false),
Question('Life is always fun', false),
Question('Life is always sad', false),
Question('Life is a mixture of good and bad', true),
Question('Life is a mixture of happiness and sadness', true),
Question('Nothing lasts forever in life', true),
Question('change is the only constant in life', true),
Question('Failure happens only when you stop trying', true),
Question('Life is never an equal opportunities provider', true),
Question('sometimes even a problem is an opportunity in life', true),
Question(
'Death is the only guaranteed in life rest everything is just a probability',
true),
Question('Age is just a number, not a limitation', true),
];
nextQuestion() {
if (_qno < _questionBank.length - 1) {
_qno++;
}
}
String getQuestion() {
return _questionBank[_qno].question;
}
bool getAnswer() {
return _questionBank[_qno].answer;
}
bool isFinished() {
if (_qno >= _questionBank.length - 1) {
return true;
} else {
return false;
}
}
void reset() {
_qno = 0;
}
}

[Link]
class Question {
String question = " ";
bool answer = true;

Question(String que, bool ans) {


question = que;
answer = ans;
}
}

For adding a hex color in flutter we need to add a code before the hex code Color(0xFFhexcode);
import 'package:flutter/[Link]';

void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
),
);
}

class MyApp extends StatefulWidget {


@override
_State createState() => _State();
}

class _State extends State<MyApp> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text('HEX Color Code in Flutter')),
backgroundColor: Color(0xFFFFB007),
),
body: Center(
child: Text(
'Scope India',
style: TextStyle(
fontSize: 35,
fontWeight: [Link],
color: Color(0xFFF00107),
),
),
),
);
}
}

TextFormFields and Form Validation

Steps for validation using TextFormField and Form widget


1.​ Create a Form with a [Link] Form widget acts as a container for grouping and
validating multiple form fields. When creating the form, provide a GlobalKey, this will uniquely
identify the Form and will allow validation of the form at a later stage.

2.​ Add TextFormFields with validation logic. The TextFormField widget renders a text field
for input and can display validation errors when they occur. The input can be validated by
providing a validator() function to the TextFormField. If the user’s input isn’t valid, the validator
function returns a String containing an error message. If there are no errors, the validator must
return null.

3.​ Create a button to validate and submit the form. When the user attempts to submit the
form, check if the form is valid. If it is, display a success message. If it isn’t (the text field has no
content) display the error message. To validate the form, use the _formKey created in step 1. You
can use the _formKey.currentState() method to access the FormState, which is automatically
created by Flutter when building a Form.

The FormState class contains the validate() method. When the validate() method is called, it runs
the validator() function for each text field in the form. If everything looks good, the validate()
method returns true. If any text field contains errors, the validate() method rebuilds the form to
display any error messages and returns false.

import 'package:flutter/[Link]';

void main() => runApp(ValidationApp());

class ValidationApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
final appTitle = 'Flutter Form ';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF8E3179),
centerTitle: true,
title: Text(appTitle),
),
body: MyCustomForm(),
),
);
}
}

class MyCustomForm extends StatefulWidget {


@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}

// Create a corresponding State class, which holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
final _nameController = TextEditingController(); //name
final _phoneController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _addressController = TextEditingController();
final _vehicleController = TextEditingController();
final _districtController = TextEditingController();
final _cityController = TextEditingController();
final _stateController = TextEditingController();
final _pinCodeController = TextEditingController();

// Create a global key that uniquely identifies the Form widget


// and allows validation of the form.
final _formKey = GlobalKey<FormState>();

String dropdowntype = 'Vehicle Category';

var type = [
'Vehicle Category',
'Cars',
'Bikes',
];

String? validatepassword(value) {
if ([Link]) {
return "Enter Password";
} else if ([Link] < 5) {
return "Should Be Atleast 5 Characters";
} else if ([Link] > 10) {
return "Should Not Be More Than 10 Characters";
}
}

@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Container(
child: GestureDetector(
child: Scaffold(
backgroundColor: [Link],
body: Padding(
padding: const [Link](20.0),
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: [Link],
children: [
Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 20.0),
TextFormField(
controller: _nameController,
keyboardType: [Link],
autofocus: false,
validator: (value) {
if (value!.isEmpty) {
return 'Enter Name';
} else if ([Link] < 3) {
return "Should Be Atleast 3 Characters";
} else {
return null;
}
},
decoration: InputDecoration(
hintText: "Name",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _phoneController,
autofocus: false,
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'(^(?:[+0]9)?[0-9]{10,10}$)')
.hasMatch(value)) {
return "Enter Valid Mobile number";
} else {
return null;
}
},
keyboardType: [Link],
decoration: InputDecoration(
hintText: "Mobile No",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _emailController,
keyboardType: [Link],
autofocus: false,
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$')
.hasMatch(value)) {
return "Enter Valid Email Address";
} else {
return null;
}
},
decoration: InputDecoration(
hintText: "Email id",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _passwordController,
autofocus: false,
validator: validatepassword,
obscureText: true,
keyboardType: [Link],
decoration: InputDecoration(
hintText: "Password",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
Column(children: [
Container(
padding: const [Link](
right: 180.0,
),
child: DropdownButton(
value: dropdowntype,
icon:
const Icon(Icons.keyboard_arrow_down),
items: [Link]((String type) {
return DropdownMenuItem(
value: type,
child: Text(
type,
style: TextStyle(
fontSize: 15,
color: [Link]),
),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
dropdowntype = newValue!;
});
},
),
),
]),
SizedBox(height: 12.0),
TextFormField(
controller: _vehicleController,
keyboardType: [Link],
validator: (value) {
if (value!.isEmpty) {
return "Enter Vehicle Number";
} else {
return null;
}
},
decoration: InputDecoration(
hintText: "Vehicle Number",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _addressController,
autocorrect: true,
autofocus: false,
keyboardType: [Link],
validator: (value) {
if (value!.isEmpty) {
return "Enter Address";
}
},
decoration: InputDecoration(
hintText: "Address",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _cityController,
autocorrect: true,
autofocus: false,
validator: (value) {
if (value!.isEmpty) {
return "Enter City";
}
},
keyboardType: [Link],
decoration: InputDecoration(
hintText: "City",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _districtController,
autocorrect: true,
autofocus: false,
keyboardType: [Link],
validator: (value) {
if (value!.isEmpty) {
return "Enter District";
}
},
decoration: InputDecoration(
hintText: "District",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _stateController,
autocorrect: true,
autofocus: false,
keyboardType: [Link],
validator: (value) {
if (value!.isEmpty) {
return "Enter State";
}
},
decoration: InputDecoration(
hintText: "State",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 12.0),
TextFormField(
controller: _pinCodeController,
autofocus: false,
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'(^(?:9)?[0-9]{6,10}$)')
.hasMatch(value)) {
return "Enter Valid Pincode";
} else {
return null;
}
},
keyboardType: [Link],
decoration: InputDecoration(
hintText: "Pin Code",
hintStyle: TextStyle(
fontSize: 15, color: [Link]),
errorBorder: UnderlineInputBorder(
borderRadius: [Link](6.0),
borderSide: BorderSide(
color: [Link],
),
),
),
),
SizedBox(height: 35.0),
Center(child:Container(
padding: const [Link](
left: 0.0, top: 40.0),
child: new ElevatedButton(
child: const Text('Submit'),
onPressed: () {
// It returns true if the form is valid, otherwise returns false
if (_formKey.currentState!.validate()) {
print("form validation is successfully submitted");
}
},
))),
],
),
),
])))))));
}
}

Date Formatting

add intl: in [Link] to use date formatting. Standard Formats as below:


- add intl: in [Link]

import 'package:intl/[Link]';

void main() {
var now = [Link]();
var todaysDate = DateFormat("dd-MM-yyyy").format(now);
print(todaysDate); //30-06-2021

var todayDate = DateFormat("yyyy-MM-dd hh:mm:ss").format(now);


print(todayDate);

var timeNow = DateFormat("H:m:s").format(now);


print(timeNow); //15:22:52

var pastDate = [Link]("2000-05-10 22:19:23");

var futureDate = [Link]("2025-05-10 22:19:23");

print([Link](futureDate)); // => true

print([Link](futureDate)); // => false

var date1 = [Link]("2000-05-10 22:19:23");


var date2 = [Link]("2001-05-10 22:19:23");
var dayDifference = [Link](date1);
print("Difference in days: ${[Link]}");

var dateOne = [Link]("2021-06-30 20:18:04");

var newDate = [Link](new Duration(days: 2));

print(newDate);

DateTime _date = [Link]();


final DateFormat _dateFormatter = DateFormat('MMM dd, yyyy');
var formattedDate = _dateFormatter.format(_date);
print(formattedDate);
}
Custom Pattern
Slivers

A sliver is a special widget that is different from other widgets like Container, Text, ListView, GridView,
or SingleChildScrollView. A sliver is a portion of a scrollable area that you can define to behave in a
special way. Sliver widgets have a few additional properties compared to normal widgets. You can use
slivers to achieve custom scrolling effects, for eg:- elastic scrolling.

Widgets like Container, ListView, Text, etc. that we use inside a Scaffold extend the abstract class
RenderConstrainedBox but slivers extend the abstract class RenderSliver hence slivers cannot be used
directly in Scaffold. We will have to add a CustomScrollView,it is a type of scrollView which has a
property named slivers. This can hold an array of widgets that extend the abstract class RenderSliver.

These widgets have some capabilities beyond those of simple widgets (widgets which extend
RenderConstrainedBox) such as expanding and shrinking the app bar, control over the scroll effect, a
widget with scrolling effect.

Let’s create a screen with CustomScrollView:

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Slivers"),
),
),
body: CustomScrollView(),
),
);
}
}

There are 7 Different Types of Slivers in Flutter:

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

SliverAppBar

The Scaffold has an app bar of fixed height but SliverAppBar can be added inside the slivers array in
CustomScrollView, and has all properties which are present in AppBar. Additionally, it also contains the
addon properties of dynamic height and some scrolling effect. This lets us expand or shrink the height
of the SliverAppBar while scrolling.
The SilverAppBar has a property named pinned, which is of type boolean. If we do not want to expand
or shrink with scroll, we can set this to false. Depending on the input gesture the SliverAppBar may
scroll up or down with all slivers.

There are other properties, such as expandedHeight and collapsedHeight, to control the height of
SliverAppBar while scrolling.

Eg:-

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {


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

@override
_HomePageState createState() => _HomePageState();
}

Widget build(BuildContext context) {


return Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 1')),
expandedHeight: 30,
collapsedHeight: 100,
),
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 1')),
floating: true,
),
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 2')),
floating: true,
expandedHeight: 60,
collapsedHeight: 256,
),
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 3')),
floating: true,
expandedHeight: 60,
collapsedHeight: 256,
),
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 4')),
floating: true,
expandedHeight: 60,
collapsedHeight: 256,
),
const SliverAppBar(
backgroundColor: [Link],
title: Center(child: Text('Custom Sliver App bar 5')),
floating: true,
expandedHeight: 60,
collapsedHeight: 256,
),
],
));
}
}

SliverToBoxAdapter
All Sliver widgets are put inside CustomScrollView to create special scroll effects. SliverToBoxAdapter is
also a sliver widget but it acts as a bridge between CustomScrollView and simple box widgets.

For example, SizedBox is a simple box widget which cannot be added directly in CustomScrollView.
Here comes the SliverToBoxAdapter, which is a sliver widget that can hold widgets of the box type.

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {


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

@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Center(child: Text('Sliver Example')),
pinned: true,
expandedHeight: 80,
),
SliverToBoxAdapter(
child: SizedBox(
height: 1500,
child: Center(
child: Text('SliverToBoxAdapter'),
),
),
),
SliverAppBar(
title: Center(child: Text('SliverAppBar')),
pinned: true,
backgroundColor: [Link],
expandedHeight: 80,
),
],
));
}
}

SliverList
In CustomScrollView, when you want to render a list of items which can be scrolled vertically, a
SliverList is used. It has a property named delegate which accepts SliverChildBuilderDelegate. SliverList
is especially used when the number of items in the list is not known — such as in cases where you
need to render the list containing responses from the server API.

SliverChildBuilderDelegate has a property childCount of type integer which takes in the length of an
array. This works similarly to [Link].

Add this code inside the class:

List<Widget> widgetList = <Widget>[];


String content = '';

Widget rowWidget(String text) {


return Padding(
padding: [Link](20),
child: Text(
text,
style: [Link](context).textTheme.bodyText1,
),
);
}

List<Widget> listOfText() {
for (int i = 0; i < 100; i++) {
content = 'Row no. ${i}'.toString();
[Link](rowWidget(content));
}

return widgetList;
}

And this code is part of CustomScrollView:


slivers: <Widget> [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => listOfText()[index],
childCount: listOfText().length),
)
]

SliverFixedExtentList

When the number of items to be rendered in the list view of CustomScrollView is already known,
SliverFixedExtentList is used. It has a property named delegate which accepts SliverChildListDelegate
value. The SliverChildListDelegate can hold other types of widgets like arrays.

So if you need to show a list of widgets with a predefined number, we can add all those widgets inside
SliverChildListDelegate. It is equivalent to Listview.

ItemExtent is the property that tells us the height of the widget inside SliverChildListDelegate.

slivers: <Widget> [
SliverFixedExtentList(
itemExtent: 100,

delegate: SliverChildListDelegate([ //equivalent to Listview


Container(color: [Link],),
Container(color: [Link],),
Container(color: [Link],)
]),

),
]

SliverGrid

In CustomScrollView, if you want to render a list of items which can be scrolled horizontally, a
SliverGrid is used. It has a property named delegate which accepts SliverChildBuilderDelegate. Like
SliverList, SliverGrid is also used when the number of items on the list is not known such as in cases
when there is a need to render a list containing responses from a server API.

SliverChildBuilderDelegate has a property childCount of type integer, which takes the length of an
array. It is equivalent to [Link].

The code below shows us how it looks behind the scenes:


child: CustomScrollView(
slivers: <Widget>[
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 2),
delegate:
SliverChildBuilderDelegate(//equivalent to [Link]
(context, index) {
return Container(
height: 100,
color: [Link][100 * (index % 9)],
child: Text('Pink $index'),
);
}, childCount: 17),
)
],
),

[Link]

When the number of items in the list is already known and can be scrolled horizontally,
[Link] is used. Its children can take in a list of widgets.

In SliverGrid the number of widgets in one horizon is not fixed, and the height of a widget is decided
by the property maxCrossAxisExtent and childAspectRatio. For example, if maxCrossAxisExtent is 100
and childAspectRatio is 1 then the height of the widget will be 100, and if childAspectRatio is 2 then
the height will also be halved.

The formula: Height of a widget = maxCrossAxisExtent/ childAspectRatio.

This is what [Link] looks like coded in:

return Scaffold(
body: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
[Link](
maxCrossAxisExtent: 100,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 1,
children: [
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
),
Container(
color: [Link],
)
])
],
),
));

[Link]

[Link] is used when the number of items is fixed. Like [Link], [Link] also
renders a list horizontally, but it allows us to set the number of widgets to be rendered in
[Link]. Like [Link], it too has the same property — children — which takes in a list
of widgets. The number of widgets in one horizon can be fixed by setting the crossAxisCount property.
Suppose you want to have only 3 items in one row horizontally; you will set the crossAxisCount to 3.

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {


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

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
[Link](
crossAxisCount: 3,
crossAxisSpacing: 10,
childAspectRatio: 1,
mainAxisSpacing: 10,
children: [
Container(
color: [Link],
child: Text("container"),
),
Container(
color: [Link],
child: Text("container"),
),
Container(
color: [Link],
child: Text("container"),
),
Container(
color: [Link],
child: Text("container"),
),
Container(
color: [Link],
child: Text("container"),
),
Container(
color: [Link],
child: Text("container"),
)
]),
],
),
));
}
}

Combined Slivers

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


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

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Slivers"),
),
),
body: CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
pinned: true,
expandedHeight: 250.0,
flexibleSpace: FlexibleSpaceBar(
title: Text('Demo'),
),
),
SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200.0,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
childAspectRatio: 4.0,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: [Link],
color: [Link][100 * (index % 9)],
child: Text('Grid Item $index'),
);
},
childCount: 20,
),
),
SliverFixedExtentList(
itemExtent: 35.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: [Link],
color: [Link][100 * (index % 9)],
child: Text('List Item $index'),
);
},
childCount: 20,
),
),
],
),
),
);
}
}

Check by omitting the ‘childCount:’ can give infinite number of children

Color codes

import 'package:flutter/[Link]';

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

/// App Widget


class MyApp extends StatefulWidget {
/// Initialize app
MyApp();

@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


/// Widget
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,

/// Home
home: Homepage(),
);
}
}

class Homepage extends StatefulWidget {


@override
_HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {


Color _color1 = Color(0xFFFF7F50);
Color _color2 = [Link](255, 255, 187, 0);
Color _color3 = HexColor("#80bb00");

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: _color1,
title: Text(
"Custom Colors in Flutter",
style: TextStyle(color: [Link]),
),
),
body: Container(
width: [Link],
child: Column(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: [
// Color 1
Container(
width: [Link],
height: 30.0,
color: _color1,
alignment: [Link],
child: Text("Custom Color")),

// Color 2
Container(
width: [Link],
height: 30.0,
color: _color2,
alignment: [Link],
child: Text("Color from ARGB")),

// Color 3
Container(
width: [Link],
height: 30.0,
color: _color3,
alignment: [Link],
child: Text("Color from Hex string")),
])));
}
}

// Converts hex string to color


class HexColor extends Color {
static int _getColor(String hex) {
String formattedHex = "FF" + [Link]().replaceAll("#", "");
return [Link](formattedHex, radix: 16);
}

HexColor(final String hex) : super(_getColor(hex));


}

Color Codes in Flutter

ARGB component (alpha, red, green, and blue)

Color c = const [Link](0xff, 0xff, 0x7f, 0x50);


Color c = const [Link](255, 66, 165, 245);

RGBO (Red,Green,Blue and Opacity)


Color c = const [Link](66, 165, 245, 1.0);

BMI Calculator

Initial program for building a layout for BMI calculator

import 'package:flutter/[Link]';

void main() => runApp(LayoutApp());

class LayoutApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(scaffoldBackgroundColor: Color(0xFF0A0E90)),
home: InputPage(),
);
}
}
class InputPage extends StatefulWidget {
@override
_InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
'Layout App',
)),
),
body: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
)),
Expanded(
child: Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
)),
],
)),
Expanded(
child: Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
)),
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
)),
Expanded(
child: Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
)),
],
)),
],
));
}
}

Refactoring the app

Now we can see that the code has been repeated in many places to build the cards(containers), so to
keep our code DRY(Do Not Repeat) we can do the following:

Select the ‘flutter outline’ from the rightside menu and keep the cursor on the container and press
<ctr> and click, now the flutter outline will appear from the rightside. Now select
Container’ and right click on it, select ‘Extract Widget’. Give a suitable name(first letter in Caps) and
click ‘refactor’. This will create a new widget with the name we gave, you can check it by going down.
We can now replace the code set with this widget where ever applicable. The code will look like this:

import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

void main() => runApp(LayoutApp());

class LayoutApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(scaffoldBackgroundColor: Color(0xFF0A0E90)),
home: InputPage(),
);
}
}

class InputPage extends StatefulWidget {


@override
_InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
'Layout App',
)),
),
body: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(child: Boxes()),
Expanded(child: Boxes())
],
)),
Expanded(
child: Row(
children: <Widget>[Expanded(child: Boxes())],
)),
Expanded(
child: Row(
children: <Widget>[
Expanded(child: Boxes()),
Expanded(child: Boxes())
],
)),
],
));
}
}

class Boxes extends StatelessWidget {


const Boxes({
Key? key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: Color(0xFF0A0E35),
),
);
}
}

Now imagine we want to pass the colour of this card using a constructor for this widget to receive
the colour property. Add the constructor as below:-

class Boxes extends StatelessWidget {


Boxes([Link]);
Color colour;
@override
Widget build(BuildContext context) {
return Container(
margin: [Link](15.0),
decoration: BoxDecoration(
Borde rRadius: [Link](15.0),
color: colour,
),
);
}
}

And change the rest as below to pass the colour:-

import 'package:flutter/[Link]';
import 'package:flutter/[Link]';

void main() => runApp(LayoutApp());

class LayoutApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(scaffoldBackgroundColor: [Link]),
home: InputPage(),
);
}
}

class InputPage extends StatefulWidget {


@override
_InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(
child: Text(
'Layout App',
)),
),
body: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(child: Boxes(Color(0xFF0A0E35))),
Expanded(child: Boxes(Color(0xFF0A0E35)))
],
)),
Expanded(
child: Row(
children: <Widget>[Expanded(child: Boxes(Color(0xFF0A0E35)))],
)),
Expanded(
child: Row(
children: <Widget>[
Expanded(child: Boxes(Color(0xFF0A0E35))),
Expanded(child: Boxes(Color(0xFF0A0E35)))
],
)),
],
));
}
}

Create a bottom container after the last expanded widget

Expanded(child: Boxes([Link])),
],
)),
Container(
height: 80.0,
width: [Link],
color: [Link],
margin: [Link](13.0),
Now pass the bottom container’s height as a variable after the import statements.

double bottomContainerHeight = 70.0;

Assign like below

Container(
height: bottomContainerHeight,
width: [Link],

Same way create a variable to pass colour to the cards

const colour = Color(0xFF0A0E35);

Now change as below

class Boxes extends StatelessWidget {


Boxes([Link]);
Color colour;
@override
Widget build(BuildContext context) {
return Container(
margin: [Link](15.0),
decoration: BoxDecoration(
borderRadius: [Link](15.0),
color: colour,
),
);
}
}

Synchronous & Asynchronous programming

synchronous operation: A synchronous operation blocks other operations from executing until it
completes whereas asynchronous operation allows other operations to execute before it completes.
Create dart file under flash_dart project directory

Async / future

void main() {
invokeTasks();
}

void invokeTasks() {
task1();
task2();
task3();
task4();
}

void task1() {
String result = 'task 1 data';
print('Task 1 complete');
}

void task2() {
String result = 'task 2 data';
print('Task 2 complete');
}

void task3() {
String result = 'task 3 data';
print('Task 3 complete');
}

void task4() {
String result = 'task 4 data';
print('Task 4 complete');
}

Now this runs synchronously - meaning one after the other, that is the way functions are executed.
Now in a scenario where a function execution is going to take a very long time than the one after it, it
will delay the code execution. We can use asynchronous method to do this as below:-

Change:

import 'dart:io';

void task2() {
Duration delay = Duration(seconds: 3);
sleep(delay);
String result = 'task 2 data';
print('Task 2 complete');
}
Now run this and observe the delay - this is still synchronous, change it as follows to include an
asynchronous method.

void task2() {
Duration delay = Duration(seconds: 2);
[Link](delay, () {
String result = 'task 2 data';
print('Task 2 complete');
});
}

Run the file and see asynchronous in work

What is Future?

‘Future’ is a promise for a data to be received in future. You can specifically mention what type of
data will be returned as below.

Future<String> task2() async {

It is comparable to ordering something in a restaurant, you pay and get a receipt and while you wait
for your order you can continue with other things like making a call, checking facebook, etc..when
your order is ready, your order no. is called and you can claim the item. Here the ‘receipt’ is the
Future, when you ordered you got a receipt which is nothing but a promise for something that is
receivable in future.

Now what if task4 needs and an output from task2, for example:
void main() {
invokeTasks();
}
void invokeTasks() {
task1();
String? task2results = task2();
task3();
task4(task2results);
}
void task1() {
String result = 'task 1 data';
print('Task 1 complete');
}
String? task2() {
Duration delaySeconds = Duration(seconds: 4);
String? r;
[Link](delaySeconds, () {
r = 'task 2 data';
print('Task 2 complete');
});
return r;
}

void task3() {
String result = 'task 3 data';
print('Task 3 complete');
}

void task4(t2d) {
String result = 'task 4 data';
print('Task 4 completed with $t2d');
}

Result from task4 will be: Task 4 completed with null

Now rectify this as below so that task3 & 4 will wait for task2 to complete
Async / Await

void main() {
invokeTasks();
}
void invokeTasks() async {
task1();
String t = await task2();
task3();
task4(t);
}
void task1() {
String result = 'task 1 data';
print('Task 1 complete');
}
Future task2() async {
Duration delay = Duration(seconds: 3);
late String r;
await [Link](delay, () {
r = "task 2 data";
print('Task 2 complete');
});
return r;
}
void task3() {
String result = 'task 3 data';
print('Task 3 completed');
}
void task4(t2d) {
String result = 'task 4 data';
print('Task 4 completed with $t2d');
}

FIREBASE:

Follow firebase instruction (separate for Android & IOS)

example (after creating & adding the App to firebase)

[Link]
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/[Link]';
import 'package:learning/[Link]';
import '[Link]';

void main() async {


[Link]();
await [Link]();

runApp(MaterialApp(
title: 'Flutter Firebase',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
home: HomePage(),
));
}

class HomePage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(child: Text('Home Page')),
),
body: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 150.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Login Page'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
SizedBox(
height: 80.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Sign Up'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => RegistrationPage()),
);
},
),
],
),
),
);
}
}

[Link]

import 'package:flutter/[Link]';
import 'package:firebase_auth/firebase_auth.dart';
late String name;
late String password;
late String emailId;
late String mobileNo;
final _auth = [Link];

class RegistrationPage extends StatefulWidget {


@override
_State createState() => _State();
}

class _State extends State<RegistrationPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Registration Screen'),
),
body: Padding(
padding: [Link](15),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
name = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Name',
hintText: 'Enter Your Name',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
mobileNo = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Mobile No',
hintText: 'Enter mobile no',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
emailId = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter Email id',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
password = i;
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
),
),
),
ElevatedButton(
child: Text('Register'),
onPressed: () async {
try {
final newUser = _auth.createUserWithEmailAndPassword(
email: emailId, password: password);
if (newUser != null) {
print(newUser);
[Link](
context,
MaterialPageRoute(
builder: (context) => RegistrationPage()),
);
}
} catch (e) {
print(e);
}
},
)
],
),
)));
}
}

[Link]

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/[Link]';

FirebaseAuth auth = [Link];


User? user;
String emailId = "";
String password = "";

class LoginPage extends StatefulWidget {


@override
_State createState() => _State();
}

class _State extends State<LoginPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login Screen'),
),
body: Padding(
padding: [Link](15),
child: Column(
children: <Widget>[
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
emailId = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'User Name',
hintText: 'Enter Your Name',
),
),
),
Padding(
padding: [Link](15),
child: TextField(
onChanged: (i) {
password = i;
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
),
),
),
ElevatedButton(
child: Text('Sign In'),
onPressed: () async {
try {
UserCredential userCredential =
await [Link](
email: emailId,
password: password,
);
user = [Link];
} on FirebaseAuthException catch (e) {
user = null;
if ([Link] == 'user-not-found') {
print('No user found for that email.');
} else if ([Link] == 'wrong-password') {
print('Wrong password provided.');
}
}
if (user != null) {
print("log in successfull");
} else
print("Login failed");
},
)
],
)));
}
}

Create a database and add a collection

Click on your project in Console, click on your app, click on ‘build’ from the left and select ‘Firestore
database’ -> ‘create database’ -> ‘start in test mode’ -> ‘Next’ -> ‘Enable’ -> ‘start collection’ -> give
name for collection -> click ‘auto id’ for generating ids automatically.
After creating collection you can add documents(records) into the collection.

Make changes in [Link]

final _firestore = [Link];

ElevatedButton(
child: Text('Register'),
onPressed: () async {
try {
final newUser = _auth.createUserWithEmailAndPassword(
email: emailId, password: password);
if (newUser != null) {
print(newUser);
_firestore.collection('user_master').add({
'email_id': emailId,
'name': name,
'mobileNo': mobileNo,
});

[Link](
context,
MaterialPageRoute(
builder: (context) => LoginPage()),
);
}
} catch (e) {
print(e);
}
},
)

[Link]

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/[Link]';
import 'package:learning/[Link]';
import 'display_users.dart';
import '[Link]';

var data;
CollectionReference users =
[Link]('user_master');

getUserData() async {
QuerySnapshot snapshot = await [Link]();
data = [Link]((doc) => [Link]()).toList();
}

void main() async {


[Link]();
await [Link]();
runApp(MaterialApp(
title: 'Flutter Navigation',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
home: HomePage(),
));
}

class HomePage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(child: Text('Home Page')),
),
body: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 150.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Login Page'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
SizedBox(
height: 80.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Sign Up'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => RegistrationPage()),
);
},
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Display Details'),
onPressed: () async {
await getUserData();
print(data);
[Link](
context,
MaterialPageRoute(builder: (context) => DisplayUsers(data)),
);
},
),
],
),
),
);
}
}

Displaying the data in a screen using ListViewBuilder.

We can use the same code from the ListViewBuilder example earlier and change it to create a new
screen as below.
display_users.dart

import 'package:flutter/[Link]';

import 'package:flutter/[Link]';

List<String> myList = [
"Antony",
"Jibin",
"Shiffin",
"Ashik",
"Arya",
"Vishnu",
"Fawas",
"Rahul",
"Koshy",
"Riya",
"Roopa"
];
// void main() {
// print(myList);
// runApp(DisplayUsers());
// }

class DisplayUsers extends StatelessWidget {


DisplayUsers([Link]);
var userData;

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ListViewBuilder',
home: Scaffold(
appBar: AppBar(
title: Center(child: const Text('User List')),
),
body: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return Container(
padding: [Link](5),
child: Column(
children: [
Container(
width: [Link],
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
)),
child: Padding(
padding: const [Link](15),
child: Text(userData[index]["name"])),
),
Container(
width: [Link],
decoration: BoxDecoration(
color: [Link],
border: [Link](
color: [Link],
)),
child: Padding(
padding: const [Link](15),
child: Text(userData[index]["mobileNo"])),
),
],
),
);
})),
);
}
}

Update/Edit : the user details: create a new file and copy paste the display_users.dart into the new
file and change the code as below. Every collection means a collection of documents, and each
document has a unique document id, we can use the document id to update the document with the
code ‘[Link][index].id’. Use index of the Listviewbuilder to access the correct record in the
snapshot.

[Link]

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/[Link]';
import 'package:learning/[Link]';
import 'package:learning/update_users.dart';
import 'display_users.dart';
import '[Link]';

CollectionReference users =
[Link]('user_master');

Future<List> getUserData() async {


QuerySnapshot snapshot = await [Link]();
var data = [Link]((doc) => [Link]()).toList();
return data;
}

void main() async {


[Link]();
await [Link]();
runApp(MaterialApp(
title: 'Flutter Navigation',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
home: HomePage(),
));
}

class HomePage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link],
title: Center(child: Text('Home Page')),
),
body: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 150.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Login Page'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
SizedBox(
height: 80.0,
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Sign Up'),
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => RegistrationPage()),
);
},
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Display Details'),
onPressed: () async {
var users = await getUserData();
print(users);
[Link](
context,
MaterialPageRoute(builder: (context) => DisplayUsers(users)),
);
},
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Update Details'),
onPressed: () async {
var users = await getUserData();
print(users);
[Link](
context,
MaterialPageRoute(builder: (context) => UpdateUsers(users)),
);
},
),
],
),
),
);
}
}

update_users.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/[Link]';
import 'package:learning/[Link]';

var name;
var mobileNo;
CollectionReference users =
[Link]('user_master');

Future<QuerySnapshot<Object?>> getUserData() async {


QuerySnapshot custSnapshot = await [Link]();
return (custSnapshot);
}

class UpdateUsers extends StatelessWidget {


UpdateUsers([Link]);

var userData;

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ListViewBuilder',
home: Scaffold(
appBar: AppBar(
title: Center(child: const Text('User List')),
),
body: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return Column(
children: [
Container(
decoration: BoxDecoration(
border: [Link](
color: [Link],
width: 5,
)),
child: Padding(
padding: const [Link](25),
child: TextField(
onChanged: (i) {
name = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: userData[index]["name"],
),
)),
),
Container(
decoration: BoxDecoration(
// color: [Link],
border: [Link](
color: [Link],
width: 5,
)),
child: Padding(
padding: const [Link](25),
child: TextField(
onChanged: (i) {
mobileNo = i;
},
decoration: InputDecoration(
border: OutlineInputBorder(),
// labelText: 'update mobile',
hintText: userData[index]["mobileNo"],
),
)),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor:
[Link]([Link])),
child: Text('Update Details'),
onPressed: () async {
QuerySnapshot snapshot = await getUserData();
dynamic docId = [Link][index].id;
print("doc Id :${docId}");
if (emailId != null && name != null) {
await users
.doc(docId)
.update({'name': name, 'mobileNo': mobileNo});
} else {
print("fields are empty");
}
},
),
],
);
})),
);
}
}

StreamBuilder - (As part of the above firebase project)

Creates a new StreamBuilder that builds itself based on the latest snapshot of interaction with the
specified stream

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/[Link]';

late String pName;

final _firestore = [Link];


final pNameController = TextEditingController();
var proName = "";

class AddProduct extends StatefulWidget {


@override
_AddProductState createState() => _AddProductState();
}

class _AddProductState extends State<AddProduct> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
title: Text('Products'),
backgroundColor: [Link],
),
body: SafeArea(
child: Column(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
StreamProducts(),
Container(
child: Row(
crossAxisAlignment: [Link],
children: <Widget>[
Expanded(
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Product name',
),
controller: pNameController,
onChanged: (value) {
proName = value;
},
),
),
TextButton(
onPressed: () async {
if (proName == null) {
proName = " ";
} else {
_firestore.collection('products').add({
'p_name': proName,
});
}
[Link]();
},
child: Text('Save'),
),
],
),
),
],
),
),
);
}
}
class StreamProducts extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _firestore.collection('products').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if ([Link]) {
final products = [Link]?.docs;
List<DisplayBox> displayBoxes = [];
for (var product in products!) {
final proNameText = product['p_name'];
final displaybox = DisplayBox(text: proNameText);
[Link](displaybox);
}
return Expanded(
child: ListView(
padding: [Link](horizontal: 10.0, vertical: 20.0),
children: displayBoxes,
),
);
}
return Text('no data');
// return Text('${[Link]}');
});
}
}

class DisplayBox extends StatelessWidget {


DisplayBox({
required [Link],
});
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: [Link](10.0),
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
Material(
borderRadius: [Link](
bottomLeft: [Link](30.0),
bottomRight: [Link](30.0),
topRight: [Link](30.0),
),
elevation: 5.0,
color: [Link],
child: Padding(
padding: [Link](vertical: 10.0, horizontal: 20.0),
child: Text(
text,
style: TextStyle(
color: Colors.black54,
fontSize: 15.0,
),
),
),
),
],
),
);
}
}

DataTable Widget

import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}

class MyApp extends StatefulWidget {


@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


List<Map> _books = [
{'id': 104, 'title': 'Flutter Basics', 'author': 'David John'},
{'id': 101, 'title': 'Advanced Flutter', 'author': 'George John'},
{'id': 103, 'title': 'Git and GitHub', 'author': 'Merlin Nick'},
{'id': 102, 'title': 'Git and GitHub', 'author': 'Benjamin Nick'}
];
int _currentSortColumn = 0;
bool _isSortAsc = true;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('DataTable Demo'),
),
body: ListView(
children: [_createDataTable()],
),
),
);
}

DataTable _createDataTable() {
return DataTable(
columns: _createColumns(),
rows: _createRows(),
sortColumnIndex: _currentSortColumn,
sortAscending: _isSortAsc,
);
}

List<DataColumn> _createColumns() {
return [
DataColumn(
label: Text('ID'),
onSort: (columnIndex, _) {
setState(() {
_currentSortColumn = columnIndex;
if (_isSortAsc) {
_books.sort((a, b) => b['id'].compareTo(a['id']));
} else {
_books.sort((a, b) => a['id'].compareTo(b['id']));
}
_isSortAsc = !_isSortAsc;
});
},
),
DataColumn(label: Text('Book')),
DataColumn(label: Text('Author'))
];
}

List<DataRow> _createRows() {
return _books
.map((book) => DataRow(cells: [
DataCell(Text('#' + book['id'].toString())),
DataCell(Text(book['title'])),
DataCell(Text(book['author']))
]))
.toList();
}
}

FutureBuilder

the FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a
Future. It is necessary for Future to be obtained earlier either through a change of state or change in
dependencies. FutureBuilder is a Widget that will help you to execute some asynchronous function
and based on that function’s result your UI will update.

FutureBuilder is Stateful by nature i.e it maintains its own state as we do in StatefulWidgets.

import 'package:flutter/[Link]';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {​

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: [Link],
),
home: HomePage(),
);
}
}

class HomePage extends StatelessWidget {


@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Future Builder Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () => [Link](
context,
MaterialPageRoute(
builder: (context) => FutureDemoPage(),
),
),
child: Text('Get Future data'),
),
),
),
);
}
}

class FutureDemoPage extends StatelessWidget {


/// Function that will return a
/// "string" after some time
/// To demonstrate network call
/// delay of [2 seconds] is used
///
/// This function will behave as an
/// asynchronous function
Future<String> getData() {
return [Link](Duration(seconds: 2), () {
return "I am data";
// throw Exception("Custom Error");
});
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Future Demo Page'),
),
body: FutureBuilder(
builder: (ctx, snapshot) {
// Checking if future is resolved or not
if ([Link] == [Link]) {
// If we got an error
if ([Link]) {
return Center(
child: Text(
'${[Link]} occurred',
style: TextStyle(fontSize: 18),
),
);

// if we got our data


} else if ([Link]) {
// Extracting data from snapshot object
final data = [Link] as String;
return Center(
child: Text(
'$data',
style: TextStyle(fontSize: 18),
),
);
}
}

// Displaying LoadingSpinner to indicate waiting state


return Center(
child: CircularProgressIndicator(),
);
},

// Future that needs to be resolved


// inorder to display something on the Canvas
future: getData(),
),
),
);
}
}

Using SQLite in Flutter App

What Is SQLite?

SQLite is a C-language library that implements a small, fast, self-contained, high-reliability,


fully-featured, SQL database engine. SQLite is the most used database engine in the world and is built
into all mobile phones and most computers and comes bundled inside countless other applications
that people use every day.

The SQLite file format is stable, cross-platform, and backwards compatible and the developers pledge
to keep it that way through the year 2050. SQLite database files are commonly used as containers to
transfer rich content between systems [1] [2] [3] and as a long-term archival format for data [4]. There
are over 1 trillion (1e12) SQLite databases in active use.

SQLite source code is in the public-domain and is free to everyone to use for any purpose.

[Link]

cupertino_icons: ^1.0.2
sqflite:
path:
path_provider:

[Link]

import 'dart:async';
import 'dart:io';
import 'package:flutter/[Link]'; // to get WidgetsFlutterBinding
import 'package:path/[Link]';
import 'package:sqflite/[Link]';
import 'package:path_provider/path_provider.dart';

void main() async {


[Link]();
print(getDatabasesPath());
Directory dir = await getApplicationDocumentsDirectory();
// print(dir);
// String path = [Link];
void createTable(db, version) {
return [Link](
'CREATE TABLE students(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
);
}

String path = [Link] + '[Link]';


print(path);
final collegeDB = openDatabase(
join(path),
onCreate: createTable,
version: 1,
);

Future<void> insertStudent(Student std) async {


final db = await collegeDB;
await [Link](
'students',
[Link](),
conflictAlgorithm: [Link],
);
}

Future<List<Student>> students() async {


final db = await collegeDB;
final List<Map<String, dynamic>> maps = await [Link]('students');
return [Link]([Link], (i) {
return Student(
id: maps[i]['id'],
name: maps[i]['name'],
age: maps[i]['age'],
);
});
}

Future<void> updatestudent(Student student) async {


final db = await collegeDB;
await [Link](
'students',
[Link](),
where: 'id = ?',
// Pass the Student's id as a whereArg to prevent SQL injection.
whereArgs: [[Link]],
);
}
Future<void> deleteStudent(int id) async {
final db = await collegeDB;
await [Link](
'students',
// Use a `where` clause to delete a specific student.
where: 'id = ?',
// Pass the Student's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}

// Create a Student and add it to the student table


var adam = Student(
id: 1,
name: 'Adam',
age: 18,
);
var eve = Student(
id: 2,
name: 'Eve',
age: 18,
);
var cain = Student(
id: 3,
name: 'Cain',
age: 18,
);
var abel = Student(
id: 4,
name: 'Abel',
age: 18,
);
await insertStudent(adam);
await insertStudent(eve);
await insertStudent(abel);
await insertStudent(cain);

print(await students()); // Prints a list of all students

// Update Adam's age and save it to the collegeDB.


adam = Student(
id: [Link],
name: [Link],
age: [Link] + 2,
);
await updatestudent(adam);

print(await students());

// Delete Adam from the collegeDB.
await deleteStudent([Link]);

print(await students());
}

class Student {
final int id;
final String name;
final int age;

Student({
required [Link],
required [Link],
required [Link],
});

// Convert a student into a Map. The keys must correspond to the names of the
// columns in the database.
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'age': age,
};
}

// Implement toString to make it easier to see information about each


// student when using the print statement.
@override
String toString() {
return 'Student{id: $id, name: $name, age: $age}';
}
}

Checkbox

A checkbox is a type of input component which holds the Boolean value. It is a GUI
element that allows the user to choose multiple options from several selections.
Here, a user can answer only in yes or no value. A marked/checked checkbox means
yes, and an unmarked/unchecked checkbox means no value. Typically, we can see
the checkboxes on the screen as a square box with white space or a tick mark. A
label or caption corresponding to each checkbox described the meaning of the
checkboxes.

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: HomePage(),
));
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


bool valuefirst = false;
bool valuesecond = false;

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Checkbox Example'),
),
body: Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
'Checkbox Example ',
style: TextStyle(fontSize: 17.0),
),
SizedBox(
width: 100,
),
Checkbox(
checkColor: [Link],
activeColor: [Link],
value: valuefirst,
onChanged: (value) {
setState(() {
valuefirst = value!;
});
},
),
Checkbox(
value: valuesecond,
onChanged: (value) {
setState(() {
valuesecond = value!;
});
},
),
],
),
SizedBox(height: 10),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
onPressed: () {
print("First box ticked: " + [Link]());
print("Second box ticked: " + [Link]());
},
child: Text("Submt"),
))
],
)
],
)),
),
);
}
}

CheckboxListTitle:

"CheckboxListTile" checkbox, which comes with header and subtitle.

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: MyHomePage(),
));
}

class MyHomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<MyHomePage> {


var days = [];
bool val = false;
bool val1 = false;
bool val2 = false;

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Checkbox with Header and Subtitle'),
),
body: Container(
padding: new [Link](22.0),
child: Column(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
'We play on ',
style: TextStyle(fontSize: 20.0),
),
CheckboxListTile(
secondary: const Icon(Icons.calendar_month),
title: const Text('Friday'),
subtitle: Text('morning'),
value: val,
onChanged: (value) {
setState(() {
val = value!;
});
},
),
CheckboxListTile(
secondary: const Icon(Icons.calendar_month),
title: const Text('Saturday'),
subtitle: Text('morning'),
value: val1,
onChanged: (value) {
setState(() {
val1 = value!;
});
},
),
CheckboxListTile(
controlAffinity: [Link],
secondary: const Icon(Icons.calendar_month),
title: const Text('Sunday'),
subtitle: Text('evening'),
value: val2,
onChanged: (value) {
setState(() {
val2 = value!;
});
},
),
ElevatedButton(
onPressed: () {
[Link]();
if (val!) {
[Link]("Friday");
}
if (val1!) {
[Link]("Saturday");
}
if (val2!) {
[Link]("Sunday");
}
print("Selected Play days are : " + [Link]());
},
child: Text("Submit"))
],
)),
),
);
}
}

Selecting multiple values in checkbox

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: [Link](),
debugShowCheckedModeBanner: false,
home: MyHomePage(title: 'Flutter Checkbox Demo'),
);
}
}

class MyHomePage extends StatefulWidget {


final String title;

MyHomePage({[Link] = 'Demo'});

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


Map<String, bool?> lightSwitches = {
'Living Room': true,
'Bedroom': false,
'Dining Room': true,
'Kitchen': true,
'Entrance': true,
};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text([Link]),
),
body: Column(children: [
Container(
padding: [Link](16.0),
child: Text('Light Switches',
style: TextStyle(
fontWeight: [Link],
fontSize: 20.0,
color: Colors.black54)),
),
Expanded(
child: SingleChildScrollView(
scrollDirection: [Link],
child: Column(
children: [Link]
.map((roomName) => CheckboxListTile(
title: Text(roomName),
value: lightSwitches[roomName],
onChanged: (bool? value) {
setState(() {
lightSwitches[roomName] = value;
});
},
))
.toList(),
),
),
flex: 1),
Container(
padding: [Link](16.0),
child: Text('Light Icons',​
style: TextStyle(
fontWeight: [Link],
fontSize: 20.0,
color: Colors.black54)),
),
Expanded(
child: SingleChildScrollView(
scrollDirection: [Link],
child: Row(
children: [Link]
.map((roomName) => LightBulbCard(
room: roomName,
on: lightSwitches[roomName],
))
.toList(),
),
),
flex: 1),
]));
}
}

class LightBulbCard extends StatelessWidget {


const LightBulbCard({
[Link] = true,
[Link] = 'Room Name',
});

final bool? on;


final String room;

@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: [Link](color: Color(0xffeeeeee), width: 2.0),
color: Colors.white38,
borderRadius: [Link]([Link](8.0)),
boxShadow: [
BoxShadow(
color: Colors.white10,
blurRadius: 4,
spreadRadius: 2,
offset: Offset(0, 2),
),
],
),
margin: [Link](8),
height: 200,
width: 200,
child: Column(
mainAxisAlignment: [Link],
children: [
Center(
child: Icon(
[Link],
size: 100.0,
color: on! ? [Link] : [Link],
)),
SizedBox(
height: 20.0,
),
Text(
room,
style: TextStyle(
fontWeight: [Link],
fontSize: 24.0,
color: Colors.black54),
),
],
),
);
}
}

Radio button

import 'package:flutter/[Link]';

void main() => runApp(MyApp());

/// This Widget is the main application widget.


class MyApp extends StatelessWidget {
static const String _title = 'Radio Button Example';

@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
enum Sports { Badminton, Football, Tennis }

class MyStatefulWidget extends StatefulWidget {


@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {


var selection;
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: const Text('Badminton'),
leading: Radio(
value: [Link],
groupValue: selection,
onChanged: (value) {
setState(() {
selection = value;
});
},
),
),
ListTile(
title: const Text('Football'),
leading: Radio(
value: [Link],
groupValue: selection,
onChanged: (value) {
setState(() {
selection = value;
});
},
),
),
ListTile(
title: const Text('Tennis'),
leading: Radio(
value: [Link],
groupValue: selection,
onChanged: (value) {
setState(() {
selection = value;
});
},
),
),
Text("Selection : ${selection}"),
],
);
}
}

Using getter/setter Class


class GetterSetter {
late String gName;

String get getName {


return gName;
}

set setName(String name) {


gName = name;
}
}

void main() {
GetterSetter instance = GetterSetter();

[Link] = "first user";


print("Welcome ${[Link]}");

[Link] = "second user";


print("Welcome ${[Link]}");

Shortcut: Inside class definition use <alt> + <Insert> to create


1.​ Constructor
2.​ Setter
3.​ Getter
4.​ Getter/setter
5.​ Etc..

Adding Push Notifications to a Flutter App using Firebase Cloud Messaging

Add dependency

dependencies:
firebase_messaging: ^14.1.1

import 'package:firebase_messaging/firebase_messaging.dart';

Edit your app manifest

Add the following to your app's manifest:

A service that extends FirebaseMessagingService. This is required if you want to do any message
handling beyond receiving notifications on apps in the background. To receive notifications in
foregrounded apps, to receive data payload, to send upstream messages, and so on, you must extend
this service.

<service
android:name=".[Link]"
android:exported="false">
<intent-filter>
<action android:name="[Link].MESSAGING_EVENT" />
</intent-filter>
</service>
Native Messaging

import 'package:flutter/[Link]';
import 'package:native_notify/native_notify.dart';

void main() {
[Link]();
[Link](2173, 'Mt1BSDDDaGb5DZ22Tt15jy');
runApp(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: 'Flutter Demo',
theme: ThemeData(
primarySwatch: [Link],
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {


const MyHomePage({Key? key, required [Link]}) : super(key: key);

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text([Link]),
),
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: [Link](context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: const Icon([Link]),
),
);
}
}

You might also like