0% found this document useful (0 votes)
12 views39 pages

Flutter 4, 5

Flutter is an open-source toolkit by Google for building cross-platform applications using a single codebase in the Dart programming language. Key features include hot reload for instant updates, a rich set of customizable widgets, and easy access to native features and SDKs. The framework supports both mobile and desktop app development, simplifying the process compared to traditional native frameworks for Android and iOS.

Uploaded by

anjacboy
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)
12 views39 pages

Flutter 4, 5

Flutter is an open-source toolkit by Google for building cross-platform applications using a single codebase in the Dart programming language. Key features include hot reload for instant updates, a rich set of customizable widgets, and easy access to native features and SDKs. The framework supports both mobile and desktop app development, simplifying the process compared to traditional native frameworks for Android and iOS.

Uploaded by

anjacboy
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
You are on page 1/ 39

Unit –IV

Flutter

• Flutter is a toolkit created by Google that lets developers build apps for mobile,
web, and desktop using the same code.
• Flutter is an open source Platform.
• It uses the Dart programming language and comes with ready-to-use widgets
for designing user interfaces.
• The Cross-platform development framework has the ability to write one code
and can deploy on the various platform (Android, iOS, and Desktop).
• Flutter’s special feature, hot reload, allows developers to see changes instantly
as they code, making development faster.
Why Flutter?
In general, creating a mobile application is a very complex and challenging task.
There are many frameworks available, which provide excellent features to develop
mobile applications. For developing mobile apps, Android provides a native framework
based on Java and Kotlin language, while iOS provides a framework based on
Objective-C/Swift language. Thus, we need two different languages and frameworks to
develop applications for both OS. Today, to overcome form this complexity, there are
several frameworks have introduced that support both OS along with desktop apps.
These types of the framework are known as cross-platform development tools.

Features of Flutter
Flutter gives easy and simple methods to start building beautiful mobile and desktop
apps with a rich set of material design and widgets. Here, we are going to discuss its
main features for developing the mobile framework.

Open-Source: Flutter is a free and open-source framework for developing mobile


applications.

Cross-platform: This feature allows Flutter to write the code once, maintain, and can
run on different platforms. It saves the time, effort, and money of the developers.

Hot Reload: Whenever the developer makes changes in the code, then these changes
can be seen instantaneously with Hot Reload. It means the changes immediately visible
in the app itself. It is a very handy feature, which allows the developer to fix the bugs
instantly.

Accessible Native Features and SDKs: This feature allows the app development
process easy and delightful through Flutter's native code, third-party integration, and
platform APIs. Thus, we can easily access the SDKs on both platforms

Minimal code: Flutter app is developed by Dart programming language, which uses
JIT and AOT compilation to improve the overall start-up time, functioning and
accelerates the performance. JIT enhances the development system and refreshes the
UI without putting extra effort into building a new one.

Widgets: The Flutter framework offers widgets, which are capable of developing
customizable specific designs. Most importantly, Flutter has two sets of widgets:
Material Design and Cupertino widgets that help to provide a glitch-free experience on
all platforms.

Comparison of other mobile app development framework:


Flutter Widgets

Whenever you are going to code for building anything in Flutter, it will be inside a
widget. The central purpose is to build the app out of widgets. It describes how your
app view should look like with their current configuration and state. When you made
any alteration in the code, the widget rebuilds its description by calculating the
difference of previous and current widget to determine the minimal changes for
rendering in UI of the app.

Widgets are nested with each other to build the app. It means the root of your app is
itself a widget, and all the way down is a widget also. For example, a widget can display
something, can define design, can handle interaction, etc.
Types of Widget

We can split the Flutter widget into two categories:

1. Visible (Output and Input)


2. Invisible (Layout and Control)

Visible widget

The visible widgets are related to the user input and output data. Some of the important
types of this widget are:

Text
A Text widget holds some text to display on the screen. We can align the text widget
by using textAlign property, and style property allow the customization of Text that
includes font, font weight, font style, letter spacing, color, and many more. We can use
it as like below code snippets.

Invisible widget

The invisible widgets are related to the layout and control of widgets. It provides
controlling how the widgets actually behave and how they will look onto the screen.
Some of the important types of these widgets are:

Column

A column widget is a type of widget that arranges all its children's widgets in a vertical
alignment. It provides spacing between the widgets by using
the mainAxisAlignment and crossAxisAlignment properties. In these properties, the
main axis is the vertical axis, and the cross axis is the horizontal axis.

Row

The row widget is similar to the column widget, but it constructs a widget horizontally
rather than vertically. Here, the main axis is the horizontal axis, and the cross axis is
the vertical axis.

Flutter User Interface:


State Management Widget

In Flutter, there are mainly two types of widget:

o StatelessWidget
o StatefulWidget

StatefulWidget

A StatefulWidget has state information. It contains mainly two classes: the state
object and the widget. It is dynamic because it can change the inner data during the
widget lifetime. This widget does not have a build() method. It
has createState() method, which returns a class that extends the Flutters State Class.
The examples of the StatefulWidget are Checkbox, Radio, Slider, InkWell, Form, and
TextField.

StatelessWidget

The StatelessWidget does not have any state information. It remains static throughout
its lifecycle. The examples of the StatelessWidget are Text, Row, Column, Container,
etc.

Built in widgets:
Flutter Scaffold

The Scaffold is a widget in Flutter used to implements the basic material design visual
layout structure. It is quick enough to create a general-purpose mobile application and
contains almost everything we need to create a functional and responsive Flutter apps.
This widget is able to occupy the whole device screen. In other words, we can say that
it is mainly responsible for creating a base to the app screen on which the child widgets
hold on and render on the screen. It provides many widgets or APIs for showing Drawer,
SnackBar, BottomNavigationBar, AppBar, FloatingActionButton, and many more.

The Scaffold class is a shortcut to set up the look and design of our app that allows us
not to build the individual visual elements manually. It saves our time to write more
code for the look and feel of the app. The following are the constructor and
properties of the Scaffold widget class.

1. appBar: It is a horizontal bar that is mainly displayed at the top of the Scaffold
widget. It is the main part of the Scaffold widget and displays at the top of the screen.
Without this property, the Scaffold widget is incomplete. It uses the appBar widget that
itself contains various properties like elevation, title, brightness, etc.
2. body: It is the other primary and required property of this widget, which will display
the main content in the Scaffold. It signifies the place below the appBar and behind
the floatingActionButton & drawer.

3. drawer: It is a slider panel that is displayed at the side of the body. Usually, it is
hidden on the mobile devices, but the user can swipe it left to right or right to left to
access the drawer menu. It uses the Drawer widget properties slides in a horizontal
direction from the Scaffold edge to show navigation links in the application. An
appropriate icon for the drawer is set automatically in an appBar property.
Flutter Container

The container in Flutter is a parent widget that can contain multiple child
widgets and manage them efficiently through width, height, padding, background color,
etc. It is a widget that combines common painting, positioning, and sizing of the child
widgets. It is also a class to store one or more widgets and position them on the screen
according to our needs. Generally, it is similar to a box for storing contents. It allows
many attributes to the user for decorating its child widgets, such as using margin,
which separates the container with other contents.

If this widget does not contain any child widget, it will fill the whole area on the
screen automatically. Otherwise, it will wrap the child widget according to the
specified height & width. It is to note that this widget cannot render directly without
any parent widget. We can use Scaffold widget, Center widget, Padding widget, Row
widget, or Column widget as its parent widget.

1. child: This property is used to store the child widget of the container. Suppose we
have taken a Text widget as its child widget that can be shown in the below example:

Container(

child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),


)

2. color: This property is used to set the background color of the text. It also changes
the background color of the entire container. See the below example:

Container(

color: Colors.green,
child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),
)

3. height and width: This property is used to set the container's height and width
according to our needs. By default, the container always takes the space based on its
child widget. See the below code:

Container(

width: 200.0,
height: 100.0,
color: Colors.green,
child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),
)
4. margin: This property is used to surround the empty space around the container.
We can observe this by seeing white space around the container. Suppose we have used
the EdgeInsets.all(25) that set the equal margin in all four directions, as shown in the
below example:

Container(
width: 200.0,
height: 100.0,
color: Colors.green,
margin: EdgeInsets.all(20),
child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),
)

5. padding: This property is used to set the distance between the border of the
container (all four directions) and its child widget. We can observe this by seeing the
space between the container and the child widget. Here, we have used an
EdgeInsets.all(35) that set the space between text and all four container directions:

Container(
width: 200.0,
height: 100.0,
color: Colors.green,
padding: EdgeInsets.all(35),
margin: EdgeInsets.all(20),
child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),
)

6. alignment: This property is used to set the position of the child within the
container. Flutter allows the user to align its element in various ways such as center,
bottom, bottom center, topLeft, centerRight, left, right, and many more. In the below
example, we are going to align its child into the bottom right position.

Container(
width: 200.0,
height: 100.0,
color: Colors.green,
padding: EdgeInsets.all(35),
margin: EdgeInsets.all(20),
alignment: Alignment.bottomRight,
child: Text("Hello! I am in the container widget", style: TextStyle(fontSize: 25)),
)
Flutter Row and Column

In the previous sections, we have learned to create a simple Flutter application and its
basic styling to the widgets. Now, we are going to learn how to arrange the widgets
in rows and columns on the screen. The rows and columns are not a single widget;
they are two different widgets, namely Row and Column. Here, we will integrate these
two widgets together because they have similar properties that help us understand them
efficiently and quickly.

Row and column are the two essential widgets in Flutter that allows developers to align
children horizontally and vertically according to our needs. These widgets are very
necessary when we design the application user interface in Flutter.

Row Widget

This widget arranges its children in a horizontal direction on the screen. In other
words, it will expect child widgets in a horizontal array. If the child widgets need to fill
the available horizontal space, we must wrap the children widgets in an Expanded
widget.

A row widget does not appear scrollable because it displays the widgets within the
visible view. So it is considered wrong if we have more children in a row which will
not fit in the available space. If we want to make a scrollable list of row widgets, we
need to use the ListView widget.

We can control how a row widget aligns its children based on our choice using the
property crossAxisAlignment and mainAxisAlignment. The row's cross-axis will
run vertically, and the main axis will run horizontally.

Column

This widget arranges its children in a vertical direction on the screen. In other
words, it will expect a vertical array of children widgets. If the child widgets need to
fill the available vertical space, we must wrap the children widgets in an Expanded
widget.

A column widget does not appear scrollable because it displays the widgets within
the visible view. So it is considered wrong if we have more children in a column which
will not fit in the available space. If we want to make a scrollable list of column widgets,
we need to use the ListView Widget.

We can also control how a column widget aligns its children using the property
mainAxisAlignment and crossAxisAlignment. The column's cross-axis will
run horizontally, and the main axis will run vertically.
Flutter Text

A Text is a widget in Flutter that allows us to display a string of text with a single
line in our application. Depending on the layout constraints, we can break the string
across multiple lines or might all be displayed on the same line. If we do not specify
any styling to the text widget, it will use the closest DefaultTextStyle class style.

Ex:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MyTextPage()
);
}
}
class MyTextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Text Widget Example")
),
body: Center(
child:Text("Welcome to Javatpoint")
),
);
}
}

The following are the essential properties of the Text widget used in our
application:

TextAlign: It is used to specify how our text is aligned horizontally. It also controls the
text location.
TextDirection: It is used to determine how textAlign values control the layout of our
text. Usually, we write text from left to right, but we can change it using this parameter.

Overflow: It is used to determine when the text will not fit in the available space. It
means we have specified more text than the available space.

TextScaleFactor: It is used to determine the scaling to the text displayed by the Text
widget. Suppose we have specified the text scale factor as 1.5, then our text will be 50
percent larger than the specified font size.

SoftWrap: It is used to determine whether or not to show all text widget content when
there is not enough space available. If it is true, it will show all content. Otherwise, it
will not show all content.

MaxLines: It is used to determine the maximum number of lines displayed in the text
widget.

Flutter TextField

A TextField or TextBox is an input element which holds the alphanumeric data, such
as name, password, address, etc. It is a GUI control element that enables the user
to enter text information using a programmable code. It can be of a single-line text
field (when only one line of information is required) or multiple-line text field (when
more than one line of information is required).

Some of the most common attributes used with the TextField widget are as follows:

o decoration: It is used to show the decoration around TextField.


o border: It is used to create a default rounded rectangle border around TextField.
o labelText: It is used to show the label text on the selection of TextField.
o hintText: It is used to show the hint text inside TextField.
o icon: It is used to add icons directly to the TextField.

Flutter Buttons

Buttons are the graphical control element that provides a user to trigger an event such
as taking actions, making choices, searching things, and many more. They can be placed
anywhere in our UI like dialogs, forms, cards, toolbars, etc.

Buttons are the Flutter widgets, which is a part of the material design library. Flutter
provides several types of buttons that have different shapes, styles, and features.

Types of Flutter Buttons

o Flat Button
o Raised Button
o Floating Button
o Drop Down Button
o Icon Button
o PopupMenu Button
o Outline Button

1. Flat Button

It is a text label button that does not have much decoration and displayed without any
elevation. The flat button has two required properties that are: child and onPressed().
It is mostly used in toolbars, dialogs, or inline with other content. By default, the flat
button has no color, and its text is black. But, we can use color to the button and text
using color and textColor attributes, respectively.

Ex:
import 'package:flutter/material.dart';

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(
appBar: AppBar(
title: Text('Flutter FlatButton Example'),
),
body: Center(child: Column(children: <Widget>[
Container(
margin: EdgeInsets.all(25),
child: FlatButton(
child: Text('SignUp', style: TextStyle(fontSize: 20.0),),
onPressed: () {},
),
),
Container(
margin: EdgeInsets.all(25),
child: FlatButton(
child: Text('LogIn', style: TextStyle(fontSize: 20.0),),
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: () {},
),
),
]
))
),
);
}
}

2. Raised Button

It is a button, which is based on the material widget and has a rectangular body. It is
similar to a flat button, but it has an elevation that will increases when the button is
pressed. It adds dimension to the UI along Z-axis. It has several properties like text
color, shape, padding, button color, the color of a button when disabled, animation time,
elevation, etc.

EX:
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {


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

class _MyAppState extends State<MyApp> {


String msg = 'Flutter RaisedButton Example';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter RaisedButton Example'),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(msg, style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic),),
RaisedButton(
child: Text("Click Here", style: TextStyle(fontSize: 20),),
onPressed: _changeText,
color: Colors.red,
textColor: Colors.yellow,
padding: EdgeInsets.all(8.0),
splashColor: Colors.grey,
)
],
),
),
),
),
);
}
_changeText() {
setState(() {
if (msg.startsWith('F')) {
msg = 'We have learned FlutterRaised button example.';
} else {
msg = 'Flutter RaisedButton Example';
}
});
}
}
3. Floating Action Button

A FAB button is a circular icon button that triggers the primary action in our
application. It is the most used button in today's applications. We can use this button
for adding, refreshing, or sharing the content. Flutter suggests using at most one FAB
button per screen.

EX:
import 'package:flutter/material.dart';

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(
appBar: AppBar(
title: Text("FAB Button Example"),
backgroundColor: Colors.blue,
actions: <Widget>[
IconButton(icon: Icon(Icons.camera_alt), onPressed: () => {}),
IconButton(icon: Icon(Icons.account_circle), onPressed: () => {})
],
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.navigation),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
onPressed: () => {},
),
/*floatingActionButton:FloatingActionButton.extended(
onPressed: () {},
icon: Icon(Icons.save),
label: Text("Save"),
), */
),
);
}
}

4. DropDown Button

A drop-down button is used to create a nice overlay on the screen that allows the user
to select any item from multiple options. Flutter allows a simple way to implement a
drop-down box or drop-down button. This button shows the currently selected item and
an arrow that opens a menu to select an item from multiple options.

EX:
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(


home: MyApp(),
));

class MyApp extends StatefulWidget {


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

class _MyAppState extends State<MyApp> {


List<ListItem> _dropdownItems = [
ListItem(1, "GeeksforGeeks"),
ListItem(2, "Javatpoint"),
ListItem(3, "tutorialandexample"),
ListItem(4, "guru99")
];

List<DropdownMenuItem<ListItem>> _dropdownMenuItems;
ListItem _itemSelected;

void initState() {
super.initState();
_dropdownMenuItems = buildDropDownMenuItems(_dropdownItems);
_itemSelected = _dropdownMenuItems[1].value;
}

List<DropdownMenuItem<ListItem>> buildDropDownMenuItems(List listItems) {


List<DropdownMenuItem<ListItem>> items = List();
for (ListItem listItem in listItems) {
items.add(
DropdownMenuItem(
child: Text(listItem.name),
value: listItem,
),
);
}
return items;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("DropDown Button Example"),
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
padding: const EdgeInsets.all(5.0),
decoration: BoxDecoration(
color: Colors.greenAccent,
border: Border.all()),
child: DropdownButtonHideUnderline(
child: DropdownButton(
value: _itemSelected,
items: _dropdownMenuItems,
onChanged: (value) {
setState(() {
_itemSelected = value;
});
}),
),
),
),
Text("We have selected ${_itemSelected.name}"),
],
),
);
}
}

class ListItem {
int value;
String name;

ListItem(this.value, this.name);
}

Icon Button

An IconButton is a picture printed on the Material widget. It is a useful widget that


gives the Flutter UI a material design feel. We can also customize the look and feel of
this button. In simple terms, it is an icon that reacts when the user will touch it.

Ex:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Icon Button Example"),
),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
double _speakervolume = 0.0;

class MyStatefulWidget extends StatefulWidget {


MyStatefulWidget({Key key}) : super(key: key);

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {


Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(Icons.volume_up),
iconSize: 50,
color: Colors.brown,
tooltip: 'Increase volume by 5',
onPressed: () {
setState(() {
_speakervolume += 5;
});
},
),
Text('Speaker Volume: $_speakervolume')
],
);
}
}

PopupMenu Button

It is a button that displays the menu when it is pressed and then calls
the onSelected method the menu is dismissed. It is because the item from the multiple
options is selected. This button contains a text and an image. It will mainly use
with Settings menu to list all options. It helps in making a great user experience.

Ex:
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {


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

class _MyAppState extends State<MyApp> {


Choice _selectedOption = choices[0];

void _select(Choice choice) {


setState(() {
_selectedOption = choice;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('PopupMenu Button Example'),
actions: <Widget>[
PopupMenuButton<Choice>(
onSelected: _select,
itemBuilder: (BuildContext context) {
return choices.skip(0).map((Choice choice) {
return PopupMenuItem<Choice>(
value: choice,
child: Text(choice.name),
);
}).toList();
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: ChoiceCard(choice: _selectedOption),
),
),
);
}
}

class Choice {
const Choice({this.name, this.icon});
final String name;
final IconData icon;
}

const List<Choice> choices = const <Choice>[


const Choice(name: 'Wi-Fi', icon: Icons.wifi),
const Choice(name: 'Bluetooth', icon: Icons.bluetooth),
const Choice(name: 'Battery', icon: Icons.battery_alert),
const Choice(name: 'Storage', icon: Icons.storage),
];

class ChoiceCard extends StatelessWidget {


const ChoiceCard({Key key, this.choice}) : super(key: key);

final Choice choice;

@override
Widget build(BuildContext context) {
final TextStyle textStyle = Theme.of(context).textTheme.headline;
return Card(
color: Colors.greenAccent,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(choice.icon, size: 115.0, color: textStyle.color),
Text(choice.name, style: textStyle),
],
),
),
);
}
}

8. Outline Button

It is similar to the flat button, but it contains a thin grey rounded rectangle border. Its
outline border is defined by the shape attribute.

Example:

import 'package:flutter/material.dart';

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(
appBar: AppBar(
title: Text('Outline Button Example'),
),
body: Center(child: Column(children: <Widget>[
Container(
margin: EdgeInsets.all(25),
child: OutlineButton(
child: Text("Outline Button", style: TextStyle(fontSize: 20.0),),
highlightedBorderColor: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
onPressed: () {},
),
),
Container(
margin: EdgeInsets.all(25),
child: FlatButton(
child: Text('Flat Button', style: TextStyle(fontSize: 20.0),),
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: () {},
),
),
]
))
),
);
}
}

Flutter Icons

An icon is a graphic image representing an application or any specific entity


containing meaning for the user. It can be selectable and non-selectable. For example,
the company's logo is non-selectable. Sometimes it also contains a hyperlink to go to
another page. It also acts as a sign in place of a detailed explanation of the actual entity.

Flutter provides an Icon Widget to create icons in our applications. We can create icons
in Flutter, either using inbuilt icons or with the custom icons. Flutter provides the list
of all icons in the Icons class. In this article, we are going to learn how to use Flutter
icons in the application.

Icon Widget Properties

Property Descriptions

icon It is used to specify the icon name to display in the application. Generally, Flutter uses
material design icons that are symbols for common actions and items.
color It is used to specify the color of the icon.
size It is used to specify the size of the icon in pixels. Usually, icons have equal height and
width.
textDirection It is used to specify to which direction the icon will be rendered.
EX:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyIconPage(),
);
}
}

class MyIconPage extends StatefulWidget {


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

class _MyIconPageState extends State<MyIconPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Icon Tutorial'),
),
body: Column(children: <Widget>[
//icon with label below it
Container(
padding: EdgeInsets.all(30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Icon(
Icons.camera_front,
size: 70
),
Text('Front Camera'),
]),
Column(children: <Widget>[
Icon(
Icons.camera_enhance,
size: 70
),
Text('Camera'),
]),
Column(children: <Widget>[
Icon(
Icons.camera_rear,
size: 70
),
Text('Rear Camera'),
]),
]
),
)
],
)
);
}
}

Flutter Images

In this section, we are going to see how we can display images in Flutter. When you
create an app in Flutter, it includes both code and assets (resources). An asset is a file,
which is bundled and deployed with the app and is accessible at runtime. The asset can
include static data, configuration files, icons, and images. The Flutter supports many
image formats, such as JPEG, WebP, PNG, GIF, animated WebP/GIF, BMP, and
WBMP.

Displaying images is the fundamental concept of most of the mobile apps. Flutter has
an Image widget that allows displaying different types of images in the mobile
application.
How to display the image in Flutter

Step 1: First, we need to create a new folder inside the root of the Flutter project and
named it assets. We can also give it any other name if you want.

Step 2: Next, inside this folder, add one image manually.

Step 3: Update the pubspec.yaml file. Suppose the image name is tablet.png, then
pubspec.yaml file is:

assets:

- assets/tablet.png
- assets/background.png

Ex:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Image Demo'),
),
body: Center(
child: Column(
children: <Widget>[
Image.asset('assets/tablet.png'),
Text(
'A tablet is a wireless touch screen computer that is smaller than a notebook bu
t larger than a smartphone.',
style: TextStyle(fontSize: 20.0),
)
],
),
),
),
);
}
}

Flutter Layouts

The main concept of the layout mechanism is the widget. We know that flutter assume
everything as a widget. So the image, icon, text, and even the layout of your app are all
widgets. Here, some of the things you do not see on your app UI, such as rows, columns,
and grids that arrange, constrain, and align the visible widgets are also the widgets.

Types of Layout Widgets

We can categories the layout widget into two types:

1. Single Child Widget


2. Multiple Child Widget

Single Child Widgets

The single child layout widget is a type of widget, which can have only one child
widget inside the parent layout widget. These widgets can also contain special layout
functionality. Flutter provides us many single child widgets to make the app UI
attractive. If we use these widgets appropriately, it can save our time and makes the app
code more readable. The list of different types of single child widgets are:

Container: It is the most popular layout widget that provides customizable options for
painting, positioning, and sizing of widgets.

Padding: It is a widget that is used to arrange its child widget by the given padding. It
contains EdgeInsets and EdgeInsets.fromLTRB for the desired side where you want
to provide padding

Center: This widget allows you to center the child widget within itself.

Align: It is a widget, which aligns its child widget within itself and sizes it based on the
child's size. It provides more control to place the child widget in the exact position
where you need it.

Multiple Child widgets

The multiple child widgets are a type of widget, which contains more than one child
widget, and the layout of these widgets are unique. For example, Row widget laying
out of its child widget in a horizontal direction, and Column widget laying out of its
child widget in a vertical direction. If we combine the Row and Column widget, then it
can build any level of the complex widget.

Row: It allows to arrange its child widgets in a horizontal direction.


olumn: It allows to arrange its child widgets in a vertical direction.

ListView: It is the most popular scrolling widget that allows us to arrange its child
widgets one after another in scroll direction.

GridView: It allows us to arrange its child widgets as a scrollable, 2D array of widgets.


It consists of a repeated pattern of cells arrayed in a horizontal and vertical layout.

Expanded: It allows to make the children of a Row and Column widget to occupy the
maximum possible area.

Table: It is a widget that allows us to arrange its children in a table based widget.

Flutter Navigation and Routing

Navigation and routing are some of the core concepts of all mobile application, which
allows the user to move between different pages. We know that every mobile
application contains several screens for displaying different types of information. For
example, an app can have a screen that contains various products. When the user taps
on that product, immediately it will display detailed information about that product.

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 MaterialPageRoute and two
methods Navigator.push() and Navigator.pop() that shows how to navigate between
two routes. The following steps are required to start navigation in your application.

Step 1: First, you need to create two routes.

Step 2: Then, navigate to one route from another route by using the Navigator.push()
method.

Step 3: Finally, navigate to the first route by using the Navigator.pop() method.

EX:

import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Flutter Navigation',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: Colors.green,
),
home: FirstRoute(),
));
}

class FirstRoute extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Click Here'),
color: Colors.orangeAccent,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
),
);
}
}

class SecondRoute extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: Center(
child: RaisedButton(
color: Colors.blueGrey,
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back'),
),
),
);
}
}

Unit-5 Developing fully featured apps


Flutter Gestures
Gestures are an interesting feature in Flutter that allows us to interact with the mobile
app (or any touch-based device). Generally, gestures define any physical action or
movement of a user in the intention of specific control of the mobile device. Some of
the examples of gestures are:

o When the mobile screen is locked, you slide your finger across the screen to
unlock it.
o Tapping a button on your mobile screen, and
o Tapping and holding an app icon on a touch-based device to drag it across
screens.

We use all these gestures in everyday life to interact with your phone or touch-based
device.

Flutter divides the gesture system into two different layers, which are given below:

1. Pointers
2. Gestures

Pointers
Pointers are the first layer that represents the raw data about user interaction. It has
events, which describe the location and movement of pointers such as touches, mice,
and style across the screens. Flutter does not provide any mechanism to cancel or stop
the pointer-events from being dispatched further. Flutter provides a Listener widget
to listen to the pointer-events directly from the widgets layer. The pointer-events are
categories into mainly four types:
o PointerDownEvents
o PointerMoveEvents
o PointerUpEvents
o PointerCancelEvents

PointerDownEvents: It allows the pointer to contact the screen at a particular location.

PointerMoveEvents: It allows the pointer to move from one location to another


location on the screen.

PointerUpEvents: It allows the pointer to stop contacting the screen.

PointerCancelEvents: This event is sent when the pointer interaction is canceled.

Gestures
It is the second layer that represents semantic actions such as tap, drag, and scale,
which are recognized from multiple individual pointer events. It is also able to dispatch
multiple events corresponding to gesture lifecycle like drag start, drag update, and drag
end. Some of the popularly used gesture are listed below:

Tap: It means touching the surface of the screen from the fingertip for a short time and
then releasing them. This gesture contains the following events:

o onTapDown
o onTapUp
o onTap
o onTapCancel

Double Tap: It is similar to a Tap gesture, but you need to tapping twice in a short time.
This gesture contains the following events:

o onDoubleTap

Drag: It allows us to touch the surface of the screen with a fingertip and move it from
one location to another location and then releasing them. Flutter categories the drag into
two types:

1. Horizontal Drag: This gesture allows the pointer to move in a horizontal


direction. It contains the following events:
o onHorizontalDragStart
o onHorizontalDragUpdate
o onHorizontalDragEnd
2. Vertical Drag: This gesture allows the pointer to move in a vertical direction.
It contains the following events:

o onVerticalDragStart
o onVerticalDragStart
o onVerticalDragStart

Long Press: It means touching the surface of the screen at a particular location for a
long time. This gesture contains the following events:

o onLongPress

Pan: It means touching the surface of the screen with a fingertip, which can move in
any direction without releasing the fingertip. This gesture contains the following events:

o onPanStart
o onPanUpdate
o onPanEnd
Pinch: It means pinching (move one's finger and thumb or bring them together on a
touchscreen) the surface of the screen using two fingers to zoom into or out of a screen.

Firebase Overview:
Firebase is a Backend-as-a-Service(BaaS) which started as a YC11 startup. It
grew up into a next-generation app-development platform on Google Cloud Platform.
Firebase (a NoSQLjSON database) is a real-time database that allows storing a list of
objects in the form of a tree. We can synchronize data between different
devices.Google Firebase is Google-backed application development software which
allows developers to develop Android, IOS, and Web apps.

Why use Firebase?


o Firebase manages real-time data in the database. So, it easily and quickly
exchanges the data to and from the database. Hence, for developing mobile apps
such as live streaming, chat messaging, etc., we can use Firebase.
o Firebase allows syncing real-time data across all devices - iOS, Android, and
Web - without refreshing the screen.
o Firebase provides integration to Google Advertising, AdMob, Data Studio,
BigQuery DoubleClick, Play Store, and Slack to develop our apps with efficient
and accurate management and maintenance.
o Everything from databases, analytics to crash reports are included in Firebase.
So, the app development team can stay focused on improving the user
experience.
o Firebase applications can be deployed over a secured connection to the firebase
server.
o Firebase offers a simple control dashboard.
o It offers a number of useful services to choose from.

Pros and Cons of Firebase


Firebase has a lot of pros or advantages. Apart from the advantages, it has disadvantages
too. Let's take a look at these advantages and disadvantages:

Pros
o Firebase is a real-time database.
o It has massive storage size potential.
o Firebase is serverless.
o It is highly secure.
o It is the most advanced hosted BaaS solution.
o It has minimal setup.
o It provides three-way data binding via angular fire.
o It provides simple serialization of app state.
o We can easily access data, files, auth, and more.
o There is no server infrastructure required to power apps with data.
o It has JSON storage, which means no barrier between data and objects.

Cons

o Firebase is not widely used, or battle-tested for enterprises.


o It has very limited querying and indexing.
o It provides no aggregation.
o It has no map-reduce functionality.
o It cannot query or list users or stored files.

Firebase Authentication
In the present era, user authentication is one of the most important requirements for
Android apps. It is essential to authenticate users, and it is much harder if we have to
write all this code on our own. This is done very easily with the help of Firebase.

o Being able to authenticate our users securely, it offers a customized experience


to them based on their interests and preferences.
o We can ensure that they have no problems accessing their private data while
using our app from multiple devices.
o Firebase Authentication provides all the server-side stuff for authenticating the
user. Firebase Authentication becomes easy with SDK. It makes API easy to
use.
o Firebase Authentication also provides some user interface libraries which
enable screens for us when we are logging it.
o Firebase authentication supports authentication using a password, phone
numbers, popular identity provider like Google, Facebook, and Twitter, etc.
o We can sign in users to our app by using the FirebaseUI.
o It handles the UI flows for signing in user with an email address and
password, phone numbers, and popular providers, including Google
sign-In and Facebook Login.
o It can also handle cases like account recovery.
o It is not required to design a UI since it is already provided for us. It
means we don't have to write the activities.
o We can also sign-in users using the Firebase Authentication SDK to integrate
one or several sign-in methods into our app manually.

Firebase UI Authentication Method


Firebase UI Authentication is a way to add a complete sign-in system to our app, where Firebase provides user
interface to them. Firebase UI provides a drop-in auth solution which is used to implement authentication on
mobile devices and websites.

Firebase UI can be easily customized to fit with the rest of our app's visual style. It is open-source, so we are
not constrained in modifying the user experience to meet our apps need.

There are the following steps to use Firebase UI Authentication:

o Set up sign-in methods:


o Enable authentication method in the firebase console.
o For email address and password, phone number sign-in, and any identity
providers.
o We have to complete the configuration if anyone requires for identity providers.

o Setting our OAuth redirect URL.


o Customize the sign-in UI.
o For customizing the sign-in and UI, we have to set some Firebase UI options or fork the
code on GitHub.
o To perform the sign-in flow, use Firebase UI:

o Import the Firebase UI library.


o Specify the sign-in method which we want to support.
o Initiate the Firebase UI sign-in flow.

Firebase SDK Authentication Method


This is another type of authentication method. The Firebase SDK Authentication
provides methods for creating and managing users who use their email addresses and
password to sign in. SDK also handles sending password reset emails.

o We can also provide phone number authentication using SDK

oThe authentication of users by sending SMS messages to their phones.


o We can authenticate users by integrating with identity providers.

oSDK provides methods which allow users to sign-in with their Google,
Facebook, Twitter, and GitHub accounts.
o We can connect our app's existing sign-in system to the Firebase Authentication
SDK and gain access to Firebase Real-time database and other Firebase services.
o We can create a temporary anonymous account to use Firebase features, which
requires authentication

without requiring users to sign-in first.

There are the following steps to use Firebase SDK Authentication:

o Set up sign-in methods:

o We have to enable the authentication method in the Firebase console for


an email address and password or phone number sign-in and any identity
providers.
o We have to complete the configuration if anyone is required for identity
providers.
o Setting our OAuth redirect URL.
o Implementing UI flows for our sign-in methods:

o For email signing, add screens which prompt the user to type their email
addresses
o For phone number sign-in, add screens which prompt users to type their
phone number, and after that, for the code from the SMS message they
receive.
o For identity sign-in, implement the flow required by each provider.
o Passing the user's credentials to the Firebase Authentication SDK:

o Pass the user's email address and password.


o Pass the OAuth token, which was acquired from the identity provider.

Firebase: Realtime Database


The Firebase Realtime Database is a cloud-hosted database in which data is stored as
JSON. The data is synchronized in real-time to every connected client. All of our clients
share one Realtime Database instances and automatically receive updates with the
newest data, when we build cross-platform applications with our iOS, and JavaScript
SDKs.

The Firebase Realtime Database is a NoSQL database from which we can store and
sync the data between our users in real-time. It is a big JSON object which the
developers can manage in real-time. By using a single API, the Firebase database
provides the application with the current value of the data and updates to that data. Real-
time syncing makes it easy for our users to access their data from any device, be it web
or mobile.

The Realtime database helps our users collaborate with one another. It ships with
mobile and web SDKs, which allow us to build our app without the need for servers.
When our users go offline, the Real-time Database SDKs use local cache on the device
for serving and storing changes. The local data is automatically synchronized, when the
device comes online.

Key capabilities
A Real-time database is capable of providing all offline and online services. These
capabilities include accessibility from the client device, scaling across multiple
databases, and many more.

Real-time

The Firebase Real-time database uses data synchronization instead of using HTTP
requests. Any connected device receives the updates within milliseconds. It doesn't
think about network code and provides collaborative and immersive experiences.

Offline

The Firebase Database SDK persists our data to disk, and for this reason, Firebase apps
remain responsive even when offline. The client device receives the missed changes,
once connectivity is re-established.

Accessible from client devices

There is no need for an application server to access the Firebase Real-time database.
We can access it directly from a mobile device or web browser. Data validation and
security are available through the Firebase Real-time Database Security Rules,
expression-based rules executed when data is read or written.

Scaling across multiple databases

With the Firebase Real-time Database on Blaze Pricing Plan, we can support the data
needs of our app by splitting our data across multiple database instances in a single
Firebase project. Streamline authentication with Firebase authentication on our project
and authenticate users in our database instances. Controls access to data in each
database with custom Firebase real-time database rules available for each database
instance.

Other Alternatives

Apart from Firebase's real-time database, there are several alternatives that
are used.

Cloud Firestore
Cloud Firestore is a scalable and flexible database used for server development, mobile,
and web from Firebase and Google Cloud Platform.

Firebase Remote Config

It stores developer specified key-value pairs to change the behavior and appearance of
our app without requiring users to download an update.

Firebase Hosting

It is used to hosts the HTML, CSS, and JavaScript of our website as well as other
developer-provided assets like graphing, fonts, and icons.

Cloud Storage

It is used to store images, videos, and audio as well as other user-generated content.

Firestore
We have two options with Firebase, i.e., Firebase Real-time Database, which we
learned in our previous section and Cloud Firestore. Cloud Firestore is newer, but it is
not replacing the Firebase Real-time Database. Cloud Firestore is a flexible as well as
scalable NoSQL cloud database. It is used to store and sync data for client and server-
side development. It is used for mobile, web, and server development from Google
Cloud Platform and Firebase. Like the Firebase Real-time Database, it keeps syncing
our data via real-time listeners to the client app. It provides offline support for mobile
and web so we can create responsive apps that work regardless of network latency or
Internet connectivity.

Cloud Firestore also provides seamless integration with Google Cloud Platform
products and other Firebase, including cloud functions.

Features of Firestore
There are the following features of Firestore:

Security

For data, Cloud Firestore has built-in security access controls. It enables simple data
validation via a configuration language.

Datastore mode

Cloud Firestore supports the Datastore API. We don't need to make any changes to our
existing Datastore apps. We can expect similar performance characteristics and pricing
with the added benefit of strong stability.
Automatic upgrade

The Cloud Datastore database will be upgraded shortly and natively after the GA
release of Cloud Firestore. No code changes are required, and there is no downtime for
our app.

ACID transaction

Cloud Firestore has support for transactions, so if any operations in the transaction fail
(and cannot be withdrawn), then the entire transaction will fail.

Multi-region replication

With the help of automatic multi-region replication and strong stability, our data is safe
and available, even when disasters strike.

Powerful query engine

Cloud Firestore allows us to run sophisticated queries against our NoSQL data without
any degradation in performance. This gives us more flexibility to structure our data.

Built for cloud-native applications

Mobile and web applications are included by the typical workloads which collaborate
with the multi-user, retail product catalogs, IoT asset tracking, social user-profiles and
activity, communications, and gaming leaderboards.

Firebase: Cloud Storage


Cloud Storage is built for application developers who need to store and serve user-
generated content, usually big files like photos or videos. It is mostly used or developed
for photos and videos, but we might use this for other things like text files.

A powerful, cost-effective, and simple object storage service built to scale:

1. Google security, when uploading or downloading files from our firebase apps.
2. We can store images, audio, video, or other user-generated content.
3. We can use Google Cloud Storage to access the same files on the server.

It is a technology which allows for storing and managing various media content
generated by mobile app users. It is a cloud computing model which stores data on the
internet through a cloud computing provider who manages and operates data storage as
a service. It is delivered on-demand with just-in-time costs and capacity. It eliminates
buying and managing our own data storage infrastructure. It provides us agility,
durability, global scale with "anywhere, anytime" data access.

Key capabilities
Firebase Cloud Storage is capable of performing the following things:

Robust Operations

Reliability is one of the biggest advantages of the Cloud Firestore. Firebase SDKs
perform uploads and downloads regardless of network quality. Downloads and uploads
both are robust. Robust means from where it stopped, will restart from there, and save
the user time and bandwidth.

Strong security

For providing simple and intuitive authentication to the developer, Firebase SDKs for
Cloud Storage integrate with Firebase Authentication. For allowing access based on
filename, size, content type, and other metadata, we can use declarative security model.

High Scalability

Cloud Storage is built for the Exabyte scale when our app goes viral. Easily grow from
prototype to production using the same structure that powers Spotify and Google Photos.

You might also like