0% found this document useful (0 votes)
22 views

Mobile Application Development

Flutter notes

Uploaded by

Husnain Sabir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Mobile Application Development

Flutter notes

Uploaded by

Husnain Sabir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Mobile Application

Development

Course Code: SEND-3111


Credit Hour: 3
Instructor: Muhammad Mehmood Khalil
What is Android?
Android is a mobile operating system that is based on a modified version of Linux developed by startup Android, Inc. In
2005, Google purchased Android and took over its development work (as well as its development team).

Google wanted Android to be open and free; hence, most of the Android code was released under the open source
Apache License, which means that anyone who wants to use Android can do so by downloading the full Android source
code. Moreover, vendors (typically hardware manufacturers) can add their own proprietary extensions to Android and
customize Android to differentiate their products from others. This simple development model makes Android very
attractive and has thus piqued the interest of many vendors. This has been especially true for companies affected by the
phenomenon of Apple’s iPhone, a hugely successful product that revolutionized the smartphone industry. Such
companies include Motorola and Sony Ericsson, which for many years have been developing their own mobile operating
systems. When the iPhone was launched, many of these manufacturers had to scramble to find new ways of revitalizing
their products. These manufacturers see Android as a solution — they will continue to design their own hardware and use
Android as the operating system that powers it.

The main advantage of adopting Android is that it offers a unified approach to application development. Developers need
only develop for Android, and their applications should be able to run on numerous different devices, as long as the
devices are powered using Android. In the world of smartphones, applications are the most important part of the success
chain. Device manufacturers therefore see Android as their best hope to challenge the onslaught of the iPhone, which
already commands a large base of applications.
Android Version
Android Devices in the Market

Following types of devices:

➤ Smartphones

➤ Tablets

➤ E-reader devices

➤ Netbooks

➤ MP4 players

➤ Internet TVs
The Android Developer Community

Stack Overflow

Google Android Training

Android Discuss
What is Flutter?

A framework that allows you to build native cross platform (iOS, Android) apps with one
programming language and codebase.

Flutter uses a programming language called Dart. Dart focused on frontend (mobile apps, web
app) user interfaces (UI development). Dart provides Utility functions and UI elements called
widgets. In flutter everything is a widget and it works like a widget tree.

Its developed by Google


Anatomy of Android/Flutter Application
.idea = Configuration Files

Android = Android project files

Build = output of the flutter application. It is generated and managed by flutter SDK

Ios = ios project files

Lib: main file of the application and its a super important file of the project

Test: files for testing

.gitignore: It's used when we use github with our project

.metadata: its is managed by flutter and we normally don’t work with it

.package: it's also generated automatically by flutter and we don’t work with it. It managed all dependencies

.iml: it is also used to manage internal dependencies

Pubspec.yaml: Used to manage third party dependencies and packages.

Pubspec.lock: its is generated by pubspec.yaml and used to manage dependencies


Fragments
In Android, an Activity represents a single focused thing the
user can do. A Fragment represents a behavior or a portion of
user interface.
Fragments are a way to modularize your code, compose
sophisticated user interfaces for larger screens, and help scale
your application UI.
In Flutter, both of these concepts fall under the umbrella of
Widget
Intents
Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity,


broadcast receivers etc.

The dictionary meaning of intent is intention or purpose. So, it can be


described as the intention to do action.
Types of Intents
Implicit Intent doesn't specifiy the component. In such case, intent
provides information of available components provided by the
system that is to be invoked.

Explicit Intent specifies the component. In such case, intent


provides the external class to be invoked.
Widget Tree
Component of Screen

Scaffold

Appbar

title

leading

actions

flexiableSpace

SafeArea

Container
Components of Screen Con’t

Text

RichText

Column

Row

Button
Components of Screen Con’t
Scaffold: the Scaffold widget implements the basic Material Design visual layout, allowing you to easily add
various widgets such as AppBar, BottomAppBar, FloatingActionButton, Drawer, SnackBar, BottomSheet, and
more.

AppBar The AppBar widget usually contains the standard title, toolbar, leading, and actions properties (along
with buttons), as well as many customization options.

title The title property is typically implemented with a Text widget. You can customize it with other widgets such
as a DropdownButton widget.

leading The leading property is displayed before the title property. Usually this is an IconButton or BackButton.

actions The actions property is displayed to the right of the title property. It’s a list of widgets aligned to the
upper right of an AppBar widget usually with an IconButton or PopupMenuButton.
Con’t

flexibleSpace The flexibleSpace property is stacked behind the Toolbar or TabBar widget. The height is usually
the same as the AppBar widget’s height. A background image is commonly applied to the flexibleSpace
property, but any widget, such as an Icon, could be used.

SafeArea The SafeArea widget is necessary for today’s devices such as the iPhone X or Android devices with a
notch (a partial cut-out obscuring the screen usually located on the top portion of the device). The SafeArea
widget automatically adds sufficient padding to the child widget to avoid intrusions by the operating system.
You can optionally pass a minimum amount of padding or a Boolean value to not enforce padding on the top,
bottom, left, or right.

Container The Container widget is a commonly used widget that allows customization of its child widget. You
can easily add properties such as color, width, height, padding, margin, border, constraint, alignment, transform
(such as rotating or sizing the widget), and many others.

Text The Text widget is used to display a string of characters.

RichText The RichText widget is a great way to display text using multiple styles. The RichText widget takes
TextSpans as children to style different parts of the strings.
Con’t

Column A Column widget displays its children vertically. It takes a children property containing an array of
List<Widget>, meaning you can add multiple widgets. The children align vertically without taking up the full
height of the screen.

Row A Row widget displays its children horizontally. It takes a children property containing an array of
List<Widget>. The same properties that the Column contains are applied to the Row widget with the exception
that the alignment is horizontal, not vertical.

Buttons There are a variety of buttons to choose from for different situations such as RaisedButton,
FloatingActionButton, FlatButton, IconButton, PopupMenuButton, and ButtonBar.
Working with Forms and Validations

https://pub.dev/packages/form_field_validator
Working with Layout Responsiveness

https://pub.dev/packages/sizer
Row Widget

A Row is a widget used to display child widgets in a horizontal manner. The Row widget

does not scroll. If you have a line of widgets and want them to be able to scroll if there is

insufficient room, consider using a ListView Class.

If we wished to display three text widgets within a row we can create a Row widget like

below:
Row Widget
Row(

children: [

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),], )
Column Widget

A Column is a widget used to display child widgets in a vertical manner. The Column

widget does not scroll. If you have a line of widgets and want them to be able to scroll if

there is insufficient room, consider using a ListView.

If we wished to display three text widgets within a column we can create a Column widget

like below:
Column Widget
Column(

children: [

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),

Container(

color: Colors.orange,

child: Text(‘Hello Flutter’),

),], )
Column and Row have the same properties. So in
the examples below we are working in the same time
with both widgets.
What is the CrossAxis in
Row and Column

?
CrossAxisAlignment Propery

We can use the crossAxisAlignment property to


align our child widget in the desired direction,

for example, crossAxisAlignment.start would place


the children with their start edge aligned with the
start side of the cross axis.
CrossAxisAlignment.center

Place the children so that their centers align


with the middle of the cross axis.
CrossAxisAlignment.end

Place the children as close to the end of


the cross axis as possible.
TextDirection Propery

Determines the order to lay children out


horizontally and how to interpret start and
end in the horizontal direction.
What is the MainAxis in Row and
Column

?
MainAxisAlignment Propery

The positioning of the child widgets on the main axis.

MainAxisAlignment.start

Place the children as close to the start of the main axis as possible.
MainAxisAlignment.center

Place the children as close to the middle of


the main axis as possible.
MainAxisAlignment.end

Place the children as close to the end of the main


axis as possible.
MainAxisAlignment.spaceAround

Place the free space evenly between the children as well


as half of that space before and after the first and last
child.
MainAxisAlignment.spaceBetween

Place the free space evenly between the


children.
MainAxisAlignment.spaceEvenly

Place the free space evenly between the children as well


as before and after the first and last child.
SafeArea

When you put some content on the screen, you have to be


careful not to overlap them with mobile’s elements such
as: battery status, wifi indicator and other stuff like that.
SafeArea helps you to avoid this overlapping.
Expanded

To tell Flutter that a widget within a Column / Row


must take up all the remaining space you can use
Expanded. With its flex property you can control how
much space the child widget should take up.
Wrap

One of the most feared errors in Flutter is the “overflow


warning” or the “yellow line of the death”. This error
happen when the content within a Column / Row
exceeds the max size allowed. Wrap allows you to
place widget in a new line when they exceed screen’s
max size.
FloatingActionButton

This widget is often used with Scaffold widget to put a


floating action button on the screen. You can also decide
the position of the button with Scaffold’s property
floatingActionButtonLocation.
Hero

The Hero widget comes in handy when we need to apply an


animation on change route. An old route disappears and a new
route appears. This transition between routes can be animated
through hero animation.
PhotoHero widget example
Hero Animation widget example
Stack

When you need to stack widgets and create a stack of


elements, Stack widget comes to your aid. By using
Positioned widget you can position elements within the
stack. Its use is similar to the absolute value for the
display css property.
Hero Animation widget example
Dismissible

Do you want for your app a cute effect to delete items


from your ListView? Well, you need to use Dismissible
widget.
Hero Animation widget example
SizedBox

SizedBox widget is used when you need to create a box with


specific size (width / height). This widget allows to specify
the dimension that child element must have. You can also
specify an infinite dimension (double.infinite) if you want
that child element fill the entire size allowed. Another use of
SizedBox is when you need some space between Column /
Row elements.
Hero Animation widget example
DefaultTabController / TabBar / TabBarView

When you need to create a tab layouts these three widgets


will make your life easier.
● DefaultTabController is used to control the tabs within
the screen
● TabBar is used to create the list of tabs to show on your
app bar
● TabBarView allows to specify the content to show in each
tab
Hero Animation widget example
Drawer

In mobile apps is very common to have a sidebar for


menu items navigation. The Drawer widget allows
to accomplish such scenario.
Hero Animation widget example
SnackBar

Sometimes you need to warn users about something. Use


SnackBar widget whenever you need it. Pay attention to
context when you use SnackBar. If you pass Scaffold’s parent
context instead of child’s context the SnackBar wouldn’t
show up. In the example below I have used a Builder widget
to pass the correct context.
Hero Animation widget example
CircularProgressIndicator / LinearProgressIndicator

During fetching data (e.g from an external API) we need


to show up a progress indicator to user. Flutter helps us
with CircularProgressIndicator and
LinearProgressIndicator. It’s also possible to specify if the
progress bar should have a deterministic value or not.
Hero Animation widget example
Adapting to Display Orientation, Managing Changes to
Screen Orientation

A flutter plugin for Easily make Flutter apps responsive. Automatically adapt UI to
different screen sizes. Responsiveness made simple.
Sizer Parameters

● .h - Returns a calculated height based on the device


● .w - Returns a calculated width based on the device
● .sp - Returns a calculated sp based on the device
● SizerUtil.orientation - for screen orientation portrait or
landscape
● SizerUtil.deviceType - for device type mobile or tablet
Sizer Usage

Add the following imports to your Dart code: #


import 'package:sizer/sizer.dart';

Wrap MaterialApp with ResponsiveSizer widget


ResponsiveSizer(

builder: (context, orientation, deviceType) {

return MaterialApp();

)
Good Luck
Threading

Threading in Android
In Android, you can categorize all threading components into two basic categories:

1. Threads that are attached to an activity/fragment: These threads are tied to the lifecycle

of the activity/fragment and are tearminated as soon as the activity/fragment is destroyed.

2. Threads that are not attached to any activity/fragment: These threads can continue to

run beyond the lifetime of the activity/fragment (if any) from which they were spawned.
Con’t

Threading Components that Attach to an


Activity/Fragment

1. AsyncTask

2. Loaders
Con’t

2. Threading Components that Don’t Attach to an


Activity/Fragment

1. Service

2. Intent Service
Con’t

For the above two threading components,There are five types of thread are using

in Android Mobile Development which areas:-

1. Main thread

2. UI thread

3. Worker thread

4. Any thread

5. Binder thread
Main Thread

When an application is launched in Android, it creates the first thread of execution, known as the

“main” thread. The main thread is responsible for dispatching events to the appropriate user

interface widgets as well as communicating with components from the Android UI toolkit.

To keep your application responsive, it is essential to avoid using the main thread to perform any

operation that may end up keeping it blocked.


Main Thread Con’t

Network operations and database calls, as well as loading of certain components, are

common examples of operations that one should avoid in the main thread. When they are

called in the main thread, they are called synchronously, which means that the UI will

remain completely unresponsive until the operation completes. For this reason, they are

usually performed in separate threads, which thereby avoids blocking the UI while they

are being performed (i.e., they have performed asynchronously from the UI).
Main Thread
2. UI Thread

UI Thread allows your tasks to do background work and then move the results to UI elements such as

bitmaps.

Every app has its own special thread that runs UI objects such as View objects, This thread is called the

UI thread. Only objects running on the UI thread have access to other objects on that thread. Because

tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have

access to UI objects. To move data from a background thread to the UI thread, use a Handler that's

running on the UI thread.


3. Worker Thread

Worker threads are background threads. They are the


threads that are created separately, other than the UI
thread. Since blocking the UI thread is restricted
according to the rule, the user should run the child
processes and tasks in worker threads.
3. Worker Thread

Denotes that the annotated method can be called from any thread

(e.g. it is “thread-safe”.) If the annotated element is a class, then all

methods in the class can be called from any thread.


Con’t

The main purpose of this method is to indicate that you believe a method

can be called from any thread; static tools can then check that nothing you

call from within this method or class has more strict threading

requirements.
Asynchronous Threads

An asynchronous model allows multiple things to happen at


the same time. When your program calls a long-running function,
it doesn’t block the execution flow, and your program
continues to run. When the function finishes, the program knows
and gets access to the result (if there’s a need for that).
Asynchronous Threads

In an asynchronous system, the solution is to start an additional thread of


control. The first thread fetches the first file, and the second thread
fetches the second file without waiting for the first thread to finish, and
then both threads wait for their results to come back, after which they
resynchronize to combine their results.

Another example with a single-thread approach is a program that


requests a file from the OS and needs to make a mathematical operation.
Asynchronous Threads

In an asynchronous system, the program asks the OS for the file and
returns the control to the mathematical operation to be executed on the
CPU, while waiting for the file.

One approach to asynchronous programming is to make functions


that perform a slow action and take an extra argument, a callback
function. The action is started, and when it finishes, the callback function
is called with the result.
Multithreading Threading

Multithreading refers to the concurrent/parallel execution of more than one


sequential set (thread) of instructions.

On a single processor, multithreading gives the illusion of running in parallel. In


reality, the processor is switching by using a scheduling algorithm. Or, it’s switching
based on a combination of external inputs (interrupts) and how the threads have
been prioritized.

On multiple processor cores, threads are truly parallel. Individual microprocessors


work together to achieve the result more efficiently. There are multiple parallel,
concurrent tasks happening at once.
Example

A basic example of multithreading is downloading two files from


two different tabs in a web browser. Each tab uses a new thread to
download the requested file. No tab waits for the other one to finish,
they are downloading concurrently.

The following picture shows a simple explanation of concurrent


execution of a multithreaded application:
Asynchronous vs Multithreading

From the definitions we just provided, we can see that multithreading


programming is all about concurrent execution of different functions.
Async programming is about non-blocking execution between functions,
and we can apply async with single-threaded or multithreaded programming.

So, multithreading is one form of asynchronous programming.

Let’s take a simple analogy; you have a friend, and you decided to make
dinner together.
Asynchronous vs Multithreading

Async is when you say to your friend, “You go to the store and buy pasta. Let me know
when you get back, to make dinner together. Meanwhile, I’ll prepare sauce and
drinks.”

Threading is, “You boil the water. I’ll heat the tomato sauce. While the water is boiling, ask
me and I’ll put the pasta in. When the sauce is hot, you can add cheese. When both are
done, I’ll sit down and you serve dinner. Then we eat.”. In the threading analogy, we can
see the sequence of “When, Do” events, which represent the sequential set of
instructions per each person (thread).

From that analogy, we can conclude that Multithreading is about workers,


Asynchronous is about tasks.
Which one to use?

Choosing between the two programming models depends mainly on performance.

Given all possible combinations between sync/async and single/multi-threading, which


model should perform better?

In a nutshell, for large scale applications with a lot of I/O operations and different
computations, using asynchronous multithreading programming flow, will utilize
the computation resources, and take care of non-blocking functions. This is the
programming model of any OS!

With more power, comes more responsibility! So if we decided to implement this model,
we have to take care of different issues like race condition, deadlocks, shared resources,
and callbacks events.

You might also like