You are on page 1of 52

Acknowledgment

At first, Thanks to ALLAH the most merciful the most gracious, for this moment
has come and this
work has been accomplished.
Thanks to the Higher Technological Institute of 10th Ramdan for preparing me to
be a successful
Engineer and lifting me up to achieve this training in an environment that’s full of
encouragement and motivation.
My deepest gratitude is to be delivered to Dr.[Sara Reda], my role model in
engineering. she
understood the nature of my thoughts and guided me step by step till this work was
brought to
light. Endless trust in my potential guided me till the end. Thank you.
Special thanks to [Amir Mohamed] for his help and knowledge in the field of
training. Their professional
touches are sensed within every phase of this summer training.
Not to forget everyone who helped me, prayed for me, wished me luck or pushed
me forwards and
bored me a lot to help this work come to life. Thanks to my colleagues, friends,
laborers, technician
and everyone else for everything they did.
Last but never forgotten, Thanks to my dear family, for being supportive and
always by my side.
No words can express my deepest and sincere gratitude towards the love and care
you have granted
me in my hardest times. May ALLAH fill your hearts with happiness when we
share this success together.

1
"
Table of content

"
Chapter 1.......................................................................................................5
Dart Basics.....................................................................................5
1.1 DataTypes...................................................................... 5
1.1.1 List and Map :.................................................................................5
1.2 Variables............................................................................................................ 6
1.2.1 Type Syntax......................................................................................... 6
1.2.2 Final and Const:............................................................................................. 6
1.3 Operators......................................................................................................7
1.3.1 Arithmetic Operators.......................................................................................7
1.3.2 Equality and Relational Operators:..................................7
1.3.3 AssignmentOperators:.................................................................................7
1.3.4 Conditional Expressions:.......................................8
1.4 Loops:........................................................................................................8
1.4.1 Loop Control
Statements:....................................................................................................9
1.5 Decision
Making:...............................................................................................................9
1.6 Numbers:.............................................................................................9
1.6.1 Number Properties:...................................................................................... 9
1.6.2 Number Methods:..........................................................................................10
1.7 String:...............................................................................................................10
1.7.1 String Properties:.........................................................................................10
1.7.2 Methods to ManipulateStrings:.................................................................10
1.8 Lists:....................................................................................................11
1.8.2 List Properties:.................................................................................... 11
1.9Map:................................................................................................... 11
1.9.1 Map – Properties:..................................................................... 11
1.9.2 Map – Functions:...........................................................................11
Chapter 2..........................................................................12
Dart OOP.............................................................................12
2.1 Class In Dart..............................................................13

2
2.1.1 Syntax:...........................................................................................13
2.1.2 Example : Declaring A Class In Dart:.......................................13
2.2 Object In Dart.................................................................................14
2.2.1 Syntax:......................................................................................................14
2.3 Constructor In Dart................................................................................. 14
2.3.1 Example:......................................................................................15
2.4 Encapsulation In Dart..................................................................................15
2.4.1 Getter and Setter Methods......................................................16
2.5 Getter and Setter In Dart..................................................................... 16
2.5.1 Use Of Getter and Setter...............................................................16
2.6 Inheritance.....................................................................................16
2.6.1 Advantages Of Inheritance In Dart.......................................................... 16
2.6.3 Types Of Inheritance In Dart........................................................... 16
2.6 Null Safety In Dart.......................................................17
2.6.1 Non – Nullable Types.............................................................................18
2.6.2 Nullable Types.....................................................................18
2.6.3 The Assertion Operator (!)............................................................... 19
2.6.4 Late Keyword.......................................................................19
2.6.5 Benefits Of Null Safety...................................................... 20
Chapter 3 …........................................................................21
Introdaction to flutter........................................................21
3.1 Introdaction............................................................21
3.2. Features of Flutter
3.3. History
3.3 Brief history of flutter................................................
3,4. Why use Flutter?.........................................................
3.5. Flutter data structure during rendering..............................
Chapter 4..................................................................................................27
Widgets : Building Layouts................................................................... 27
4.1 Stateless Versus Stateless
Widgets.......................................................................................28
4.1.1 Stateless Widget In Code.................................................................... 29

3
4.2 Stateful Widgets..............................................................................29
4.2.1 Stateful Widgets In Code..................................................... 30
4.3 Basic Widgets...................................................................31
4.3.1 Text Widget...............................................................................................31
4.3.2 The Image Widget..................................................................32
4.3.3 Material Design..............................................................................33
4.4.3.1 Buttons...................................................................................................... 34
4.4.3.2 Scaffold.................................................................................... 35
4.4.3.3 Dialogs............................................................................................... 35
4.4.3.4 Text fields................................................................................36
4.4 Scrolling Widgets.........................................................................................36
4.4.1 ListView........................................................................................37
4.4.2 SingleChildScrollView........................................................................38
4.5 Styling and
Positioning.................................................................................................. 39
4.6 Navigator Widget.......................................................................39
Chapter 4.............................................................................................................38
Firebase........................................................................................................38
4.1 Cloud Firestore...........................................................................................40
4.1.1 Collections & Documents.................................................................... 41
4.1.2 Read Data...................................................................................................43
4.1.3 Add Documents................................................................................44
5.1.4 Updating Documents....................................................................................45
5.1.5 Removing Data........................................................................................46
5.2 Authentication.................................................................................47
5.2.9 Sign Out a User...................................................................................49
Chapter 6 API ….................................................................49:52

4
Chapter 1
Dart Basics
1.1 Data Types
The Dart language supports the following types−
• Numbers
• Strings
• Booleans
• Lists
• Maps
1.1.1 List and Map :
The data types list and map are used to represent a collection of objects. A List is
an ordered group of
objects.The Map data type represents a set of values as key-value pairs.
1.2 Variables
1.2.1 Type Syntax
A variable must be declared before it is used. Dart uses the var keyword to achieve
the same.
1.2.2 Final and Const:
The final and const keyword are used to declare constants. Dart prevents
modifying the values of a variable
declared using the final or const keyword. These keywords can be used in
conjunction with the variable’s
data type or instead of the var keyword.

5
The const keyword is used to represent a compile-time constant. Variables
declared using the const keyword
are implicitly final
1.3 Operators
the operators that are available in Dart.
• Arithmetic Operators
• Equality and Relational Operators
• Type test Operators
• Bitwise Operators
• Assignment Operators
• Logical Operators

1.3.1 Arithmetic Operators

The following table shows the arithmetic operators supported by Dart.


1) + : Add
2) − : Subtract
3) expr : Unary minus, also known as negation (reverse the sign of theexpression)
4) * : Multiply
5) / : Divide
6) ~/ : Divide, returning an integer result
7) % : Get the remainder of an integer division (modulo)
8) ++ : Increment
9) -- : Decrement

1.3.2 Equality and Relational Operators:


1) > Greater than - (A > B) is False
2) < Lesser than - (A < B) is True
3) >= Greater than or equal to - (A >= B) is False
4) <= Lesser than or equal to - (A <= B) is True
5) == Equality - (A==B) is False
6) != Not equal - (A!=B) is True
6
1.3.3 Assignment Operators:

1) = ( Simple Assignment ) : Assigns values from the right-side operand to the left
side operand
2) ??= : Assign the value only if the variable is null
3) += ( Add and Assignment ) : It adds the right operand to the left operand and
assigns the result to
the left operand.
4) ─= ( Subtract and Assignment ) : It subtracts the right operand from the left
operand and assigns the
result to the left operand.
5) *= ( Multiply and Assignment ) : It multiplies the right operand with the left
operand and assigns
the result to the left operand.
6) /= ( Divide and Assignment ) : It divides the left operand with the right operand
and assigns the
result to the left operand.
1.3.4 Conditional Expressions:
condition ? expr1 : expr2
If condition is true, then the expression evaluates expr1 (and returns its value);
otherwise, it evaluates and
returns the value of expr2.
expr1 ?? expr2
If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of
expr2t
1.4 Loops:
At times, certain instructions require repeated execution. Loops are an ideal way to
do the same. A loop

7
represents a set of instructions that must be repeated. In a loop’s context, a
repetition is termed as an iteration.
1) for Loop : The for loop is an implementation of a definite loop. The for loop
executes the code block
for a specified number of times. It can be used to iterate over a fixed set of values,
such as an array
2) for...in Loop : The for...in loop is used to loop through an object's properties.
1.4.1 Loop Control Statements:
1) break Statement : The break statement is used to take the control out of a
construct. Using break in
a loop causes the program to exit the loop. Following is an example of the break
statement.
2) continue Statement : The continue statement skips the subsequent statements in
the current iteration
and takes the control back to the beginning of the loop.
1.5 Decision Making:
Conditional constructs in Dart are classified in the following table.
1) if statement : An if statement consists of a Boolean expression followed by one
or more statements.
2) If...Else Statement : An if can be followed by an optional else block. The else
block will execute if
the Boolean expression tested by the if block evaluates to false.
3) else…if Ladder : The else…if ladder is useful to test multiple conditions.
Following is the syntax of
the same.
4) switch…case Statement : The switch statement evaluates an expression, matches
the expression’s

8
value to a case clause and executes the statements associated with that case.

1.6 Numbers:
1.6.1 Number Properties:
The following table lists the properties supported by Dart numbers.
1) Hashcode : Returns a hash code for a numerical value.
2) isFinite : True if the number is finite; otherwise, false.
3) isInfinite : True if the number is positive infinity or negative infinity; otherwise,
false.
4) isNegative : True if the number is negative; otherwise, false.
5) Sign : Returns minus one, zero or plus one depending on the sign and numerical
value of the number.
6) isEven : Returns true if the number is an even number.
7) isOdd : Returns true if the number is an odd number.
1.6.2 Number Methods:
1) Abs : Returns the absolute value of the number.
2) compareTo : Compares this to other number.
3) Floor : Returns the greatest integer not greater than the current number.
4) Remainder : Returns the truncated remainder after dividing the two numbers.
5) Round : Returns the integer closest to the current numbers.
6) toDouble : Returns the double equivalent of the number.
7) toInt : Returns the integer equivalent of the number.
8) toString : Returns the string equivalent representation of the number.
1.7 String:
1.7.1 String Properties:
9
The properties listed in the following table are all read-only.
1) isEmpty : Returns true if this string is empty.
2) Length : Returns the length of the string including space, tab and newline
characters.
1.7.2 Methods to Manipulate Strings:
1) toLowerCase() : Converts all characters in this string to lower case.
10
2) toUpperCase() : Converts all characters in this string to upper case.
3) compareTo() : Compares this object to another.
4) replaceAll() : Replaces all substrings that match the specified pattern with a
given value.
5) toString() : Returns a string representation of this object.
1.8 Lists:
A very commonly used collection in programming is an array. Dart represents
arrays in the form of List
objects. A List is simply an ordered group of objects. The dart:core library
provides the List class that
enables creation and manipulation of lists.
1.8.2 List Properties:
1) First : Returns the first element in the list.
2) isEmpty : Returns true if the collection has no elements.
3) isNotEmpty : Returns true if the collection has at least one element.
4) Length : Returns the size of the list.
5) Last : Returns the last element in the list.
6) Reversed : Returns an iterable object containing the lists values in the reverse
order.
10
7) Single : Checks if the list has only one element and returns it.

1.9 Map:
The Map object is a simple key/value pair. Keys and values in a map may be of
any type. A Map is a dynamic
collection. In other words, Maps can grow and shrink at runtime.
map_name[key] = value
1.9.1 Map – Properties:
The Map class in the dart:core package defines the following properties −
1) Keys : Returns an iterable object representing keys
2) Values : Returns an iterable object representing values
3) Length : Returns the size of the Map
4) isEmpty : Returns true if the Map is an empty Map
5) isNotEmpty : Returns true if the Map is an empty Map
1.9.2 Map – Functions:
1. addAll() : Adds all key-value pairs of other to this map.
2. clear() : Removes all pairs from the map.
3. remove() : Removes key and its associated value, if present, from the map.
4. forEach() : Applies f to each key-value pair of the map.

Chapter 2
Dart OOP
2.1 Class In Dart
11
In object-oriented programming, a class is a blueprint for creating
objects. A class defines the properties and
methods that an object will have. For example, a class called Dog might
have properties like breed, color
and methods like bark, run.
Declaring Class In Dart:
2.1.1 Syntax:
class ClassName {
// properties or fields // methods or functions
}
In the above syntax:
• The class keyword is used for defining the class.
• ClassName is the name of the class and must start with capital letter.
• Body of the class consists of properties and functions.
• Properties are used to store the data. It is also known as fields or
attributes.
• Functions are used to perform the operations. It is also known as
methods.

2.1.2 Example :
Declaring A Class In Dart:

12
In this example below, there is class Animal with three properties: name,
numberOfLegs, and lifeSpan.
The class also has a method called display, which prints out the values
of the three properties.
class Animal {
String? name; int?
numberOfLegs; int?
lifeSpan;
void display() { print("Animal name:
$name."); print("Number of Legs:
$numberOfLegs."); print("Life Span:
$lifeSpan."); }
}
2.2 Object In Dart

In object-oriented programming, an object is a self-contained unit of


code and data. Objects are created
from templates called classes. An object is made up of
properties(variables) and methods(functions). An
object is an instance of a class.
For example, a bicycle object might have attributes like color, size, and
current speed. It might have methods
like changeGear, pedalFaster, and brake.
2.2.1 Syntax:

13
ClassName objectName = ClassName();
2.3 Constructor In Dart
A constructor is a special method used to initialize an object. It is called
automatically when an object is
created, and it can be used to set the initial values for the object’s
properties. For example, the following
code creates a Person class object and sets the initial values for the name
and age properties.
Person person = Person("John", 30);
2.3.1 Example:
class Person{ String?
name; int? age;
String? subject;
double? salary;
// Constructor in short form
Person(this.name, this.age, this.subject,
this.salary);
// display method void display(){
print("Name: ${this.name}"); print("Age:
${this.age}"); print("Subject:
${this.subject}");print("Salary:
${this.salary}");
}
14
}
void main(){
Person person = Person("John", 30, "Maths", 50000.0);
person.display();
}
Output:
Name: John
Age: 30
Subject: Maths
Salary: 50000
2.4 Encapsulation In Dart
Encapsulation means hiding data within a library, preventing it from
outside factors. It helps you control
your program and prevent it from becoming too complicated.
Encapsulation can be achieved by:
• Declaring the class properties as private by using underscore(_).
• Providing public getter and setter methods to access and update the
value of private property.
2.4.1 Getter and Setter Methods
Getter and setter methods are used to access and update the value of
private property. Getter methods are
used to access the value of private property. Setter methods are used to
update the value of private property
15
2.5 Getter and Setter In Dart
2.5.1 Use Of Getter and Setter
• Validate the data before reading or writing.
• Restrict the read and write access to the properties.
• Making the properties read-only or write-only.
• Perform some action before reading or writing the properties
2.6 Inheritance
2.6.1 Advantages Of Inheritance In Dart
• It promotes reusability of the code and reduces redundant code.
• It helps to design a program in a better way.
• It makes code simpler, cleaner and saves time and money on
maintenance.
• It facilitates the creation of class libraries.
• It can be used to enforce standard interface to all children classes.
2.6.3 Types Of Inheritance In Dart
1. Single Inheritance - In this type of inheritance, a class can inherit from
only one class. In Dart, we can only
extend one class at a time.
2. Multilevel Inheritance - In this type of inheritance, a class can inherit
from another class and that class can
also inherit from another class. In Dart, we can extend a class from
another class which is already extended
from another class.
16
3. Hierarchical Inheritance - In this type of inheritance, parent class is
inherited by multiple subclasses. For
example, the Car class can be inherited by the Toyota class and Honda
class.
4. Multiple Inheritance - In this type of inheritance, a class can inherit
from multiple classes. Dart does not
support multiple inheritance. For e.g. Class Toyota extends Car, Vehicle
{} is not allowed in Dart.
2.6 Null Safety In Dart
Null Safety in simple words means a variable cannot contain a ‘null’
value unless you initialized with null
to that variable. With null safety, all the runtime null-dereference errors
will now be shown in compile time.
String name = null ; // This means the variable name has a null value.
2.6.1 Non – Nullable Types
When we use null safety, all the types are non-nullable by default. For
example, when we declare a variable
of type int, the variable will contain some integer value.
16
void main()
{int marks;
// The value of type `null` cannot be
// assigned to a variable of type
'int' marks = null;
17
}
Non-nullable variables must always be initialized with non-null values.
2.6.2 Nullable Types
To specify if the variable can be null, then you can use the nullable type
? operator, Lets see an example:
String? carName; // initialized to null by default
int? marks = 36; // initialized to non-null marks
= null; // can be re-assigned to null
Note: You don’t need to initialize a nullable variable before using it. It is
initialized to null by default.
2.6.3 The Assertion Operator (!)
Use the null assertion operator ( ! ) to make Dart treat a nullable
expression as non-nullable if you’re certain
it isn’t null.
Example:
int? someValue = 30;
int data = someValue!; // This is valid as value is non-nullable
2.6.4 Late Keyword
As we knew that all variables are non-null by default, we can use either
the ? operator or the late keyword.
Example:
String? carName; // using ? operator late
String bikeName; // using "late" keyword
18
2.6.5 Benefits Of Null Safety
• It provides a better development environment with fewer runtime
errors.
• Dart Compiler can optimize our code, which will led to smaller and
faster programs.

Chapter 3
Inrtoduaction to flutter
Flutter is an open-source mobile SDK developer can use to build native-looking
Android and
iOS applications from the same code base. Flutter has been around since 2015
when Google
introduced it and remained in the beta stage before its official launch in December
2018. Since
then, the buzz around Flutter has been growing stronger. Flutter is now the top 11
software repos

19
based on GitHub stars. Moreover, we have already seen thousands of Flutter apps
being
published on app stores. One of the most notable examples is the Xianyu app
created by Alibaba
team, used by over 50 million people.
Android provides a native framework based on Java language and iOS provides a
native
framework based on Objective-C / Shift language. However, to develop an
application
supporting both the OSs, we need to code in two different languages using two
different
frameworks. To help overcome this complexity, there exists mobile frameworks
supporting
both OS. These frameworks range from simple HTML based hybrid mobile
application
framework (which uses HTML for User Interface and JavaScript for application
logic) to
complex language specific framework (which do the heavy lifting of converting
code to native
code). Irrespective of their simplicity or complexity, these frameworks always
have many
disadvantages, one of the main drawbacks being their slow performance. In this
scenario,
Flutter – a simple and high-performance framework based on Dart language,
provides high
performance by rendering the UI directly in the operating system’s canvas rather
than through

20
native framework. Flutter also offers many ready to use widgets (UI) to create a
modern
application. These widgets are optimized for mobile environment and designing
the application
using widgets is as simple as designing HTML. To be specific, Flutter application
is itself a
widget. Flutter widgets also supports animations and gestures. The application
logic is based
on reactive programming. Widget may optionally have a state. By changing the
state of the
widget, Flutter will automatically (reactive programming) compare the widget’s
state (old and
new) and render the widget with only the necessary changes instead of re-
rendering the whole
Widget.

3.2. Features of Flutter


1. Flutter framework offers the following features to developers:
2. Modern and reactive framework.
3. Uses Dart programming language and it is very easy to learn.
4. Fast development.
5. Beautiful and fluid user interfaces.
6. Huge widget catalogue.
7. Runs same UI for multiple platforms.

21
8. High performance application
3.3 History
Flutter was first announced 4 years ago in 2015 at the Dart Developer Summit. It
was initially
called “SKY”. I think that would have been cooler. Flutter alpha (V-0.06) was
released in May
2017.Later, Google launched the 2nd preview of Flutter back in September
2018.That’s when
the developers around the world started to feel the heat. Even before the Flutter 1.0
was
announced, many Flutter apps came into the stores. Apps like – Alibaba, Google
Ads, Tencent,
reflect were proof that Flutter could be so Awesome. Finally, Google launched
Flutter 1.0, the
stable version of Flutter on 5th of December 2018.
At this launch, Google released ‘The History of Everything”. A timeline of the
world from the
Big Bang to the age of WWW. An app built with Flutter with a single code base
that can run
in any Android or IOS device smoothly. This app has smooth animations because
Flutter can
run apps with a of 120 Frames Per Second. (Others only can achieve a maximum
of 60 FPS).
To build apps with Flutter, you need to know Dart as flutter runs on the Dart
virtual machine
and flutter uses Dart as the Programming Language. Dart – A object oriented
programming

22
language developed by Google Dart was first released in 2011 and the latest stable
version
(Dart 2.2.0) was released in February 2019.Many sources mentions that Google
initially
released Dart as a alternative to Java-Script. But, in the official Dart website, they
deny it. For
dart beginners, dart devs say “You probably already know Dart, you just don’t
realize it”. Why?
because dart is a lot like java, C# or js. If you know any of those languages, you
only need to
study a few syntax changes.

3.4 Brief history of flutter

23
3.5 Why use Flutter?
3.5.1. Fast development
Flutter engineered for high development velocity. Stateful hot reload allows you to
change your
code and see it come to life is less than a second without losing the state of the app.
Flutter also
ships with a rich set of customizable widgets, all built from modem reactive
framework.
3.5.2. Expressive + Flexible UI
Flutter moves to a widget, rendering, animation and gestures into this framework
to give you to
complete control over every pixel on the screen. It means you have the flexibility
to build a
custom design.

3.5.3. Native apps for Android and IOS

24
Flutter apps follow platform conventions and interface details such as scrolling,
navigation,
icons, fonts, etc. That why apps built with Flutter features on both APP STORE
and GOOGLE
PLAY STORE.
3.5.4. Hot Reload
In flutter, very save on the app and just as you do on the web just hit a refresh and
your codes
also refresh. Imaging that Facebook SDK it would be so humongous if it would
have been
designing android and you hit a recompile. So many things to have recompile and
it would take
probably days. Unmistakably, Hot reloading is tech which is kind of necessary
when your
applications or product goes like incense crazy like Facebook
3.5.5. High Performance
Flutter doesn’t require a Javascript bridge and the speed is much faster.
3.5.6. Using Dart as a Programming Language
Dart is an object-oriented programming language that which used for writing
mobile application
code for Flutter and which contributes to the efficiency and effectiveness of app
development
flow. It is a comfortable language and uses a lot of CSS parts as well. Dart uses for
generational
garbage collection which helps in creating frames for short-lived objects. It also
helps to
allocate the objects with a single pointer bump to avoid UI jank and shutter.
3.5.7. Reduce the Third Parties

25
When using flutter, you can get complete IOS experience or Android Experience.
So they are
reducing the Third parties.
3.5.8. API. The Flutter API is very consistent
AnimationBuilder, FutureBuilder, StreamBuilder,…Once you understand them
you have no
limit. Anything is a widget. A button can use as a screen, a full page used as a
button with
animation and transformation.
3.5.9. The customizable kit of Widgets
Flutter has built with a rich and customizable set of widgets for Android, IOS and
Material
Design. The collaboration between Flutter and Google’s material design has
rendered and easily
create powerful UI experience. This help to create smooth, crisp and refined app
experience as
are available with a native app.

Chapter 4
26
Widgets : Building Layouts

4.1 Stateless Versus Stateless Widgets


A typical UI will be composed of many widgets, and some of them will never
change their properties after being
instantiated. They do not have a state; that is, they do not change by themselves
through some internal action or
stateless widgets give control of how they are built to some parent widget in the
tree.
The following is a representation of a stateless widget:

27
So, the child widget will receive its description from the parent widget and will
not change it by itself. In terms of
code, this means that stateless widgets have only final properties defined during
construction, and that's the only
thing that needs to be built on the device screen.

4.1.1 Stateless Widget In Code


class MyApp extends statelessWidget
{@override
Widget build(BuildContext context) {
18
return
MaterialApp( title:
'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
4.2 Stateful Widgets
Unlike stateless widgets, which receive a description from their parents that
persist during the widgets' lifetime,
stateful widgets are meant to change their descriptions dynamically during their
lifetimes. By definition, stateful
widgets are also immutable, but they have a company State class that represents
the current state of the widget. It is
28
shown in the following diagram:

By holding the state of the widget in a separate State object, the framework may
rebuild it whenever needed without
losing its current associated state. The element in the elements tree holds a
reference of the corresponding widget and 19 also the State object associated with
it. The State object will notify when the widget needs to be rebuilt and then
causean update in the elements tree, too.

29
4.2.1 Stateful Widgets In Code

class HomePage extends StatefulWidget {

const HomePage({super.key});

@override

State<HomePage> createState() => _HomePageState();

class _HomePageState extends State<HomePage>

{@override

Widget build(BuildContext context) {

return const Placeholder()

4.3 Basic Widgets


The basic widgets in Flutter are a good starting point, not only for their ease of use,
but also because they demonstrate
the power and flexibility of the framework, even in simple cases.
4.3.1 Text Widget
Text displays a string of text allowing styling:
Text(
"This is a text",
)

30
The most common properties of the Text widget are as follows:
1) style: A class that composes the styling of a text. It exposes properties that allow
changing the text color,
background, font family (allowing the usage of acustom font from assets; see
Chapter 3, An Introduction to
Flutter), line height, font size, and so on.
2) textAlign: Controls the text horizontal alignment, giving options such as center
aligned or justified, forexample.
3) maxLines: Allows specifying a maximum number of lines for the text that will
be truncated if the limit is
exceeded.
4) overflow: Will define how the text will be truncated on overflows, giving
5) options such as specifying a max-lines limit. It can be by adding an ellipsis at
the end, for example.

31
4.3.2 The Image Widget
Image displays an image from different sources and formats. From the docs, the
supported image formats are JPEG,
PNG, GIF, animated GIF, WebP, animated WebP, BMP, and WBMP:
Image( image:
AssetImage(
"assets/dart_logo.jpg"
),
)

Image Property:

a) height/width: To specify the size constraints of an image

b) repeat: To repeat the image to cover the available space

c) alignment: To align the image in a specific position within its bounds

d) fit: To specify how the image should be inscribed into the available space

4.3.3 Material Design


Many of the widgets in Flutter are descended in some way from a platform-specific
guideline: Material Design.
This helps the developer to follow platform specific guidelines in the easiest
possible way
4.4.3.1 Buttons
On the Material Design side, Flutter implements the following button components:
1) RaisedButton: A Material Design raised button. A raised button consists of a
rectangular piece of material
that hovers over the interface.
2) FloatingActionButton: A floating action button is a circular icon button that
hovers over content to promote
32
a primary action in the application.
3) FlatButton: A flat button is a section printed on a Material widget that reacts to
touches by splashing/rippling
with color.
4) IconButton: An icon button is a picture printed on a Material widget that reacts
to touches by
splashing/rippling.
4.4.3.2 Scaffold
Scaffold implements the basic structure of a Material Design or iOS Cupertino
visual layout. For Material Design,
the Scaffold widget can contain multiple Material Design components:
1) body: The primary content of the scaffold. Its displayed below AppBar, if any.
2) AppBar: An app bar consists of a toolbar and potentially other widgets.
3) TabBar: A Material Design widget that displays a horizontal row of tabs. This is
generally used as part of
AppBar.
4) TabBarView: A page view that displays the widget that corresponds to the
currently selected tab. Typically used in conjunction with TabBar and used as a
body widget.
4.4.3.3 Dialogs
Material Design dialogs are implemented by Flutter. On the Material Design side,
they are SimpleDialog and
AlertDialog.
4.4.3.4 Text fields
Text fields are also implemented by the TextField widget in Material Design.
display the keyboard for user input.
Some of their common properties are as follows:

33
a) autofocus: Whether the TextField should be focused automatically (if nothing
else is already focused).
b) enabled: To set the field as editable or not.
c) keyboardType: To change the type of keyboard displayed to the user when
editing.
4.4 Scrolling Widgets
* ListView * SingleChildScrollView * CustomScrollView
4.4.1 ListView
ListView is the most commonly used scrolling widget. It displays its children one
after another in the scroll direction.
In the cross axis, the children are required to fill the ListView.
There are two options for constructing a ListView:
* The default constructor takes an explicit List<Widget> of children. This
constructor is appropriate
for list views with a small number of children because constructing the List
requires doing work for
every child that could possibly be displayed in the list view instead of just those
children that are
actually visible.
* The ListView.builder constructor takes an IndexedWidgetBuilder, which builds
the children on
demand. This constructor is appropriate for list views with a large (or infinite)
number of children
because the builder is called only for those children that are actually visible.

34
This example uses the default constructor for ListView which takes an explicit
List<Widget> of children. This ListView's children are made up of Containers with
Tex:
L IST VIEW ( PADDING : CONST

E DGEINSETS.ALL(8), CHILDREN :

<WIDGET >[

CONTAINER( HEIGHT : 50, COLOR:

COLORS.AMBER[600], CHILD : CONST

CENTER(CHILD : TEXT ('E NTRY A')),

),

CONTAINER( HEIGHT : 50, COLOR:

COLORS.AMBER[500], CHILD : CONST

CENTER(CHILD : TEXT ('E NTRY B')),

),

CONTAINER( HEIGHT : 50, COLOR:

COLORS.AMBER[100], CHILD : CONST

CENTER(CHILD : TEXT ('E NTRY C')),

),

This example mirrors the previous one, creating the same list using the
ListView.builder constructor. Using the
IndexedWidgetBuilder, children are built lazily and can be infinite in number:

35
final List<String> entries = <String>['A', 'B', 'C']; final
List<int> colorCodes = <int>[600, 500, 100];
Widget build(BuildContext context) { return
ListView.builder( padding: const
EdgeInsets.all(8), itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return
Container(height
: 50, color: Colors.amber[colorCodes[index]], child:
Center(child: Text('Entry ${entries[index]}')),
);
}
);

4.4.2 SingleChildScrollView
A box in which a single widget can be scrolled.
This widget is useful when you have a single box that will normally be entirely
visible, for example a clock face in a
time picker, but you need to make sure it can be scrolled if the container gets too
small in one axis (the scroll direction).
4.5 Styling and Positioning

36
The task of positioning a child widget in a container, such as a Stack widget, for
example, is done by using other
widgets. Flutter provides widgets for very specific tasks. Centering a widget inside
a container is done by wrapping
it into a Center widget. Aligning a child widget relative to a parent can be done
with the Align widget, where you
specify the desired position through its alignment property. Another useful widget
is Padding, which allows us to
specify a space around the given child. The functionalities of these widgets are
aggregated in the Container widget,
which combines those common positioning and styling widgets to apply them to a
child directly, making the code
much cleaner and shorter.
4.6 Navigator Widget
The Navigator widget is the main player in the task of moving from one screen to
another. Most of the time, we will
be switching screens and passing data between them, which is another important
task for the Navigator widget.

Navigation in Flutter is made in a stack structure. The stack structure is suitable for
this task because its concept is
very similar to a screen's behavior:
• We have one element at the top of the stack. In Navigator, the top-most
element on the stack is the currently
visible screen of the app.
• The last element inserted is the first to be removed from the stack
(commonly refereed as last in first out
(LIFO)). The last screen visible is the first that is removed.
• Like stack, the Navigator widget's main methods are push()and pop()
37
Chapter 5
Firebase
Firebase is a Google product that provides multiple technologies for multiple
platforms.
Among its offered technologies, the important ones are as follows:
• Cloud Firestore: A powered database, with a focus on big and scalable
applications that provide
advanced query support compared to the real-time database.
• Real-time database: (non-relational database) database on the cloud. With
this, we can store and
synchronize data in real time.
• Authentication: Facilitates the development of the authentication layer of an
application, improving
user experience, and security. It enables the usage of multiple authentication
providers, such as
email/password, phone authentication, and also, Google, Facebook, and other login
systems.
5.1 Cloud Firestore
Cloud Firestore is a NoSQL document-based database provided by Firebase, which
is a mobile and web application development platform. Firestore is a cloud-hosted
database that can be accessed through various client libraries, including the Flutter
SDK. In Flutter, you can use the `cloud_firestore` package to interact with
Firestore.

Here's an example of how you can use Cloud Firestore in Flutter:

1. First, you need to add the `cloud_firestore` package to your `pubspec.yaml` file:

38
```yaml

dependencies:

cloud_firestore: ^2.5.4

```

2. Next, you need to initialize Firestore in your Flutter app. You can do this by
calling the `Firebase.initializeApp()` method in your `main()` function:

```dart

import 'package:firebase_core/firebase_core.dart';

void main() async {

WidgetsFlutterBinding.ensureInitialized();

await Firebase.initializeApp();

runApp(MyApp());

```

39
3. Once Firestore is initialized, you can access it using the `FirebaseFirestore`
class. Here's an example of how you can add a document to a Firestore collection:

import 'package:cloud_firestore/cloud_firestore.dart';

// Create a reference to the Firestore collection

CollectionReferenceusersRef=FirebaseFirestore.instance.collection('use')

// Add a new document to the collection

await usersRef.add({

'name': 'John Doe',

'email': 'johndoe@example.com',

'age': 30,

});

40
4. You can also query Firestore data using the `Query` class. Here's an example of
how you can query all documents in a Firestore collection:

import 'package:cloud_firestore/cloud_firestore.dart';

// Create a reference to the Firestore collection

CollectionReference usersRef =
FirebaseFirestore.instance.collection('users');

// Query all documents in the collection

QuerySnapshot querySnapshot = await usersRef.get();

// Loop through the documents and print their data

querySnapshot.docs.forEach((doc) {

print(doc.data());

});

These are just a few examples of how you can use Cloud Firestore in Flutter.
Firestore provides many more features, such as realtime updates, transactions, and
security rules, that you can explore in the official documentation.

41
5.1.1 Collections & Documents
Firestore stores data within "documents", which are contained within "collections".
Documents can also contain nested collections. For example, our users would each
have their own "document" stored inside the "Users" collection. The collection
method allows us to reference a collection within our code.
5.1.2 read time
In Cloud Firestore, "read time" refers to the time it takes to retrieve a document or
a set of documents from the database. Firestore provides a pricing model based on
the number of reads, writes, deletes, and data transferred from the database. The
read time is a key factor in determining the cost of using Firestore because the
more you read from the database, the more you will be charged.

Firestore provides several ways to optimize the read time and minimize the cost of
using the database. Here are some tips to improve read time:

1. *Use indexing: Firestore automatically indexes all fields in a document, but you
can create additional indexes for specific fields to speed up queries that filter or
sort by those fields. You can create indexes using the Firebase console or the
Firestore API.

2. *Limit the number of documents: When querying a collection, use the `limit()`
method to restrict the number of documents returned. This can help reduce the read
time and the amount of data transferred from the database.

3. *Use pagination**: When querying a collection, use the `startAfter()` and


`endBefore()` methods to paginate through the results. This can help reduce the
number of documents retrieved in each query and improve read time.

4. *Cache data on the client: Firestore provides built-in support for caching data on
the client, which can reduce the number of reads from the database and improve
read time. You can enable caching using the `enablePersistence()` method.

42
5. *Optimize your queries: Avoid using multiple queries to retrieve related data.
Instead, use subcollections or denormalization to store related data in a single
document or collection.

By following these best practices, you can optimize the read time and reduce the
cost of using Firestore in your Flutter app.
5.1.3 Add Documents
To add a new document to a collection, use the add method on a
CollectionReference.
The add method adds the new document to your collection with a unique auto-
generated ID. If you'd like to specify your own ID, call the set method on a
DocumentReference instead
5.1.4 Updating Documents
In Cloud Firestore, you can update an existing document by either replacing the
entire document or updating specific fields within the document. Here's how you
can update a document in Flutter using the cloud_firestore package:
1. First, create a reference to the document you want to update. You can do
this using the DocumentReference class:
dart

import 'package:cloud_firestore/cloud_firestore.dart';

// Create a reference to the document


DocumentReference docRef =
FirebaseFirestore.instance.collection('users').doc('user1');

2. You can then update the document by calling the update() method on the
DocumentReference object. The update() method takes a map of field
names and their new values:
dart

43
// Update specific fields in the document
docRef.update({
'name': 'Jane Doe',
'age': 35,
});

In this example, the name and age fields of the document will be updated with
their new values.
Alternatively, you can use the set() method to replace the entire document with
a new one. The set() method also takes a map of field names and their values:
dart

// Replace the entire document with a new one


docRef.set({
'name': 'Jane Doe',
'age': 35,
});

This will replace the entire document with a new one that contains only the name
and age fields.
Note that when you update a document, Firestore only updates the fields that
you specify. Any fields that you don't specify will remain unchanged. If you need
to remove a field from a document, you can set its value to null when updating
the document:
dart

// Remove a field from the document


docRef.update({
'address': null,
});

This will remove the address field from the document.


These are just a few examples of how you can update documents in Firestore
using Flutter. Firestore provides many more features for working with

44
documents, such as transactions and batched writes, that you can explore in the
official documentation.

5.2 Authentication
Authentication is the process of verifying the identity of a user. In Flutter, you
can use Firebase Authentication to authenticate users in your app. Firebase
Authentication provides several authentication methods, such as email and
password, Google Sign-In, Facebook Login, and more. Here's how you can
authenticate users using email and password in Flutter:
3. First, you need to add the firebase_auth package to your
pubspec.yaml file:

yaml

dependencies:
firebase_auth: ^3.0.2

4. Next, you need to initialize Firebase in your app. You can do this by calling
the Firebase.initializeApp() method in your main() function, just
like you would for Cloud Firestore:
dart

45
import 'package:firebase_core/firebase_core.dart';

void main() async {


WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
5. Once Firebase is initialized, you can authenticate users using the
FirebaseAuth class. Here's an example of how you can authenticate a
user using email and password:
import 'package:firebase_auth/firebase_auth.dart';

// Create a reference to the Firebase Authentication instance


final FirebaseAuth auth = FirebaseAuth.instance;

// Sign in the user with email and password


try {
UserCredential userCredential = await
auth.signInWithEmailAndPassword(
email: 'johndoe@example.com',
password: 'password123',
);
User user = userCredential.user;
print('User ${user.uid} signed in');
} catch (e) {
print('Failed to sign in user: $e');
}

In this example, the signInWithEmailAndPassword() method is used to


authenticate the user using their email and password. If authentication is

46
successful, the UserCredential object will contain information about the
authenticated user, including their unique user ID (uid).
6. You can also create new user accounts using the
createUserWithEmailAndPassword() method:
dart

// Create a new user with email and password


try {
UserCredential userCredential = await
auth.createUserWithEmailAndPassword(
email: 'johndoe@example.com',
password: 'password123',
);
User user = userCredential.user;
print('User ${user.uid} created');
} catch (e) {
print('Failed to create user: $e');
}
This code creates a new user with the specified email and password.
These are just a few examples of how you can use Firebase Authentication in
Flutter. Firebase Authentication provides many more features, such as
authentication state management and custom authentication methods, that you
can explore in the official documentation.

5.2.2 Sign in a user with an email address and Password:


The steps for signing in a user with a password are similar to the steps for
creating a new account. From your your
app's sign-in screen, call signInWithEmailAndPassword():

47
try {

final credential = await

FirebaseAuth.instance.signInWithEmailAndPassword(email:
emailAddress,

password: password

);

} on FirebaseAuthException catch (e)

{if (e.code == 'user-not-found')

{ print('No user found for that

email.');

} else if (e.code == 'wrong-password') {

print('Wrong password provided for that

user.');

5.2.3 Sign Out a User

To sign out a user, call signOut():

await FirebaseAuth.instance.signOut();

Chapter 6
API‘S
API:

48
API stands for Application Programming Interface. It is a set of guidelines and
standards for accessing a web-based software application or web tool. APIs enable
different software programs to communicate with each other and exchange data.

In Flutter, you can use APIs to integrate your app with external services and fetch
data from them. Here's an example of how you can use the `http` package to make
API calls in Flutter:

1. First, you need to add the `http` package to your `pubspec.yaml` file:

```yaml

dependencies:

http: ^0.13.4

```

2. Next, you can use the `http` package to make HTTP requests to an API. Here's
an example of how you can make a GET request to the GitHub API to fetch
information about a user:

49
import 'dart:convert';

// Make a GET request to the GitHub API

var response = await


http.get(Uri.parse('https://api.github.com/users/johndoe'));

// Parse the JSON response

var data = jsonDecode(response.body);

// Print the user's name

print('User: ${data['name']}');

```

In this example, the `http.get()` method is used to make a GET request to the
GitHub API to fetch information about the user `johndoe`. The `jsonDecode()`
method is used to parse the JSON response, and the user's name is printed to the
console.

3. You can also use the `http` package to make other types of HTTP requests, such
as POST, PUT, and DELETE. Here's an example of how you can make a POST
request to an API to create a new user:

50
import 'package:http/http.dart' as http;

import 'dart:convert';

// Define the user data

var userData = {

'name': 'Jane Doe',

'email': 'janedoe@example.com',

};

// Make a POST request to create a new user

var response = await http.post(

Uri.parse('https://api.example.com/users'),

headers: {'Content-Type': 'application/json'},

body: jsonEncode(userData),

);

// Parse the JSON response

var data = jsonDecode(response.body);

// Print the new user's ID


51
print('New user ID: ${data['id']}');

This code creates a new user by making a POST request to the API with the user's
data in JSON format. The `jsonEncode()` method is used to convert the user data to
JSON, and the `headers` parameter is used to specify the content type of the
request.

These are just a few examples of how you can use APIs in Flutter using the `http`
package. APIs provide many more features and endpoints that you can explore in
their respective documentation.

52

You might also like