Note2 Flutter
Note2 Flutter
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
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.
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.
”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.
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.
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.
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.
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.
Close project > customize > All Settings > SDK Tools > Android SDK command-line tools > OK > apply
- 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
Building an App From Scratch: A Simple App with a single child widget
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(MyApp());
}
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.
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());
}
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’
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
[Link]
import 'package:my_app/widgets/[Link]';
import 'package:flutter/[Link]';
void main() {
runApp( SomeApp());
}
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]';
@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"),
),
),
);
}
}
- 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]';
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
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"),
),
),
),
),
);
}
flutter:
uses-material-design: true
assets:
- images/[Link]
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
import 'package:flutter/[Link]';
Now Change the Columns to rows and see the changes and play around with different values
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]';
"[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),)),
],
),
),
),
));
}
}
Stateful widgets
[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(),
),
));
}
@override
Widget build(BuildContext context) {
return Container();
}
}
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(),
),
));
}
@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]'),
),
)),
],
);
}
}
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.
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();
}
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
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(),
),
));
}
@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.
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,
)),
)
],
),
),
),
);
}
}
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
void main() {
runApp(ListViewApp());
}
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());
}
--------****************---------
Final code
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
void main() {
runApp(BuildContainer());
}
@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:
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]()
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]';
void main() {
print(myList);
runApp(ListViewBuilder());
}
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());
}
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.
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.
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)
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]';
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());
}
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);
class Student {
String name;
String state;
Student({required [Link], required [Link]});
}
What is an Iterable?
Eg:-
Instead use
void main() {
Iterable<int> it = [1, 2, 3];
int i = [Link](1);
print(i);
}
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);
}
}
import 'package:flutter/[Link]';
void main() {
runApp(SearchListApp());
}
// 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());
}
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());
}
import 'package:flutter/[Link]';
int _curr = 0;
void main() {
runApp(MyApp());
}
@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])),
]));
}
}
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.
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.
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.
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()));
}
@override
Widget build(BuildContext context) {
// getting the orientation of the app
orientation = [Link](context).orientation;
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
import 'package:flutter/[Link]';
A custom ElevatedButton with child assigned a function to create a widget to show row with separate
contents
import 'package:flutter/[Link]';
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,
);
GestureDetector
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(
home: GestureDetectorScreen(),
));
}
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]';
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]';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
@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,
- 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
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]';
@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]';
[Link]
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
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());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
home: MyAppHome(),
);
}
}
'[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],
),
),
),
),
),
],
),
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(),
));
}
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');
},
),
),
],
),
);
}
}
import 'package:flutter/[Link]';
void main() {
runApp(
const MaterialApp(
title: 'Returning Data',
home: HomeScreen(),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Returning Data Demo'),
),
body: const Center(
child: SelectionButton(),
),
);
}
}
@override
State<SelectionButton> createState() => _SelectionButtonState();
}
// 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()),
);
// After the Selection Screen returns a result, hide any previous snackbars
// and show the new result.
[Link](context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$result')));
}
}
@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.'),
),
)
],
),
),
);
}
}
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]';
resizeToAvoidBottomInset
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
Quizapp
[Link]
import 'package:flutter/[Link]';
import 'package:quizapp/[Link]';
import 'package:rflutter_alert/rflutter_alert.dart';
void main() {
runApp(QuizApp());
}
@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;
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(),
),
);
}
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]';
// 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();
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
import 'package:intl/[Link]';
void main() {
var now = [Link]();
var todaysDate = DateFormat("dd-MM-yyyy").format(now);
print(todaysDate); //30-06-2021
print(newDate);
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.
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Slivers"),
),
),
body: CustomScrollView(),
),
);
}
}
[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());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}
@override
_HomePageState createState() => _HomePageState();
}
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());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}
@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].
List<Widget> listOfText() {
for (int i = 0; i < 100; i++) {
content = 'Row no. ${i}'.toString();
[Link](rowWidget(content));
}
return widgetList;
}
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,
),
]
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].
[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.
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());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Sliver example',
home: HomePage(),
);
}
}
@override
_HomePageState createState() => _HomePageState();
}
Combined Slivers
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@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,
),
),
],
),
),
);
}
}
Color codes
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@override
_MyAppState createState() => _MyAppState();
}
/// Home
home: Homepage(),
);
}
}
@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")),
])));
}
}
BMI Calculator
import 'package:flutter/[Link]';
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]';
@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:-
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
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.
Container(
height: bottomContainerHeight,
width: [Link],
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');
});
}
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.
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');
}
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:
[Link]
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/[Link]';
import 'package:learning/[Link]';
import '[Link]';
runApp(MaterialApp(
title: 'Flutter Firebase',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: [Link],
),
home: HomePage(),
));
}
[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];
[Link]
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/[Link]';
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.
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();
}
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());
// }
@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');
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');
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");
}
},
),
],
);
})),
);
}
}
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]';
DataTable Widget
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
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.
import 'package:flutter/[Link]';
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: [Link],
),
home: HomePage(),
);
}
}
@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),
),
);
What Is SQLite?
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';
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,
};
}
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(),
));
}
@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:
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(
home: MyHomePage(),
));
}
@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"))
],
)),
),
);
}
}
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'),
);
}
}
MyHomePage({[Link] = 'Demo'});
@override
_MyHomePageState createState() => _MyHomePageState();
}
@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),
]));
}
}
@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]';
@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 }
void main() {
GetterSetter instance = GetterSetter();
Add dependency
dependencies:
firebase_messaging: ^14.1.1
import 'package:firebase_messaging/firebase_messaging.dart';
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());
}
@override
State<MyHomePage> createState() => _MyHomePageState();
}
@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]),
),
);
}
}