0% found this document useful (0 votes)
7 views84 pages

Introduction to Flutter SDK Overview

Flutter is an open-source UI SDK by Google for creating applications across multiple platforms using a single codebase. It offers advantages like fast development, high performance, and a rich set of customizable UI components, while also having some disadvantages such as larger app sizes and limited third-party libraries. The document also covers Flutter's architecture, the Dart programming language, and essential widgets and project structure.

Uploaded by

mainak2003patra
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)
7 views84 pages

Introduction to Flutter SDK Overview

Flutter is an open-source UI SDK by Google for creating applications across multiple platforms using a single codebase. It offers advantages like fast development, high performance, and a rich set of customizable UI components, while also having some disadvantages such as larger app sizes and limited third-party libraries. The document also covers Flutter's architecture, the Dart programming language, and essential widgets and project structure.

Uploaded by

mainak2003patra
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

Unit - 2

Introduction to Flutter
Introduction to Flutter
Flutter is an open-source UI software development kit (SDK) created by Google for
building natively compiled applications for mobile (iOS & Android), web, desktop
(Windows, macOS, Linux), and embedded devices from a single codebase.

What is an SDK?
SDK stands for Software Development Kit. It is a collection of tools, libraries,
documentation, and sample code that developers use to build applications for a
specific platform, framework, or service.

What is Open Source UI :


Open-source UI (User Interface) refers to design components, frameworks, or
libraries that are freely available for developers to use, modify, and distribute. These
UI resources are typically released under open-source licenses (such as MIT, GPL, or
Apache), allowing the community to contribute, improve, and customize them.
Advantages or key features of flutter
1. Single Codebase : Write one codebase for multiple platforms (Android, iOS,
Web, Desktop).Saves time, effort, and development costs.
2. Fast Development with Hot Reload : Hot Reload allows developers to see
code changes instantly without restarting the [Link] up UI design,
debugging, and testing.
3. High Performance : Uses Dart language, which compiles to native code for
fast execution. Flutter's rendering engine, Skia, enables smooth animations.
4. Beautiful & Customizable UI : Comes with a rich set of Material Design
(Android) and Cupertino (iOS) [Link] customizable widgets to create
stunning UI designs.
5. Strong Community & Google Support : Backed by Google, with frequent
updates and improvements. Huge developer community with tons of open-
source plugins and libraries.
6. Native-Like Performance
• Unlike traditional cross-platform frameworks, Flutter doesn’t use a JavaScript
bridge, leading to better performance.
• Apps run directly on the device with smooth transitions.
7. Cost-Effective Development : Reduces the need for separate teams for
Android and iOS development. Faster development means lower overall costs.
[Link] & Desktop Support : Flutter extends beyond mobile apps; you can build
web, desktop, and embedded applications.A true multi-platform framework.
9. Wide Range of Plugins & Packages : Thousands of ready-to-use plugins
available on [Link]. Easy integration with Firebase, APIs, databases, and third-
party services.
10. Future-Proof & Growing Popularity : Companies like Google, Alibaba, eBay,
BMW use [Link] updates make it a future-ready framework.
Key Highlights of Flutter
Disadvantages of Flutter
[Link] App Size
• Flutter apps tend to be larger in size compared to native apps.
• This is due to the built-in widgets and Flutter engine bundled with the app.
2. Limited Third-Party Libraries & Native Features : Although Flutter has a
growing ecosystem, some third-party plugins may not be [Link] native
features (like Bluetooth, NFC, or advanced camera controls) may require
additional development effort.
3. Slower Updates for Native Features : Flutter does not immediately support
the latest native OS features (iOS & Android).Developers might need to wait for
Flutter to add support or use workarounds.
4. Limited Game Development Support
• Flutter is not ideal for high-performance gaming apps that require heavy
graphics processing.
• Lacks direct support for game engines like Unity or Unreal Engine.

5. Learning Curve for Native Developers


• Developers coming from Java/Kotlin (Android) or Swift/Objective-C (iOS)
may find Dart and Flutter’s widget-based UI challenging at first.
• Flutter’s declarative UI approach is different from traditional UI
development.
How does it work? Native Apps
How does it work? Native Apps
➢The platform, which can be Android or iOS, exposes a series of OEM(Original
Equipment Manufacturer) widgets used by the app to build the UI.
➢Those widgets are fundamental because they give our app the capabilities to
paint the UI, use the canvas and respond to events such as finger taps.
➢ If needed to access any apps such as bluetooth, then one needs to interact
with native API exposed by the platform.
➢ Not possible to have single codebase, OEM widgets and their API are different
for Android and iOS architectures.
Using Bridges : ReactJS
Using Bridges : ReactJS
1. ReactJS is a Reactive web framework which tries to solve the above problem by
adding a bridge in the middle that takes care of the communication with the
platform.

[Link] bridge always exposes the same interface to the app so that it doesn’t care
anymore about the OS it’s running on.

[Link] bridge has an implementation of OEMs and APIs for each platform to allow
the app to correctly work in many environments.

Disadvantage :
[Link] bottleneck that slows down the execution and thus the performances
might drop due to the presence of Bridge.
Flutter Approach
[Link] uses its own very efficient rendering engine, called Skia, to paint the UI so
that OEM widgets are not needed anymore.

[Link] produces native ARM code for the machine.

[Link] launch, App loads flutter library, Any rendering, event handling is sent
to Flutter Compiler, which is faster than bridge.

4.A minimal Flutter app is about 4.4 MB on Android and 10.9 MB on iOS.

[Link] not follow rules imposed by OEM, even to pixel level is controlled by
user.
Flutter Architecture
[Link] comes with full fledged SDK for building apps. That includes tools to create
UI, widgets for both Android devices as well as iOS devices.

[Link] android apps uses Material Design based themes and Widgets, where as iOS
apps uses Cupertino based themes and widgets.

[Link] uses Dart for both server side and client side development and its
completely open-source and object-oriented programming language.

[Link] the flexibility of dart language combined with C++ flutter core makes the app
behave very close to the native ones in terms of performance.
[Link] does not use native components in any form, so developers don’t
have to make bridges for communicating with them
[Link] draws the interface on its own. Buttons, text, media elements,
background all this is drawn inside the Skia graphics engine in Flutter2
Why Flutter uses Dart
OOP style: The vast majority of developers have object-oriented programming
skillsand thus Dart would be easy to learn as it adopts most of the common
OOP patterns
Performances: In order to guarantee high performances and avoid frame
dropping during the execution of the app, there’s the need of a high
performanceand predictable language and Dart promises that through powerful
memory allocator
Productivity: Flutter allows developers to write Android, iOS, web and desktop
apps with a single codebase keeping the same performances, aspect and
feeling in each platform.
Flutter and Dart are developed by Google so rich support.
Dart had additional novel features which is eye-candy, they are,
1 Tree-shaking optimization
2 Hot reload feature
3 Package manager with mandatory documentation and the possibility to play
with
the code using DartPad
4 DevTools, a collection of debugging and performance tools
5 Code documentation generator tool
6 Support for JIT and AOT compilation.
Scaffold
In Dart, specifically in Flutter, a Scaffold is a widget that provides a basic layout
structure for an app's visual interface.
It serves as a container for common UI elements such as:
AppBar (top navigation bar)
Body (main screen content)
FloatingActionButton (FAB button)
BottomNavigationBar (bottom navigation)
Drawer (side navigation menu)
SnackBars (temporary message pop-ups)
Basic Widgets
1. Text Widget
2. Container Widget
3. Row and Column Widgets
4. Image Widget
5. ElevatedButton (Button)
6. TextField Widget
7. ListView Widget
8. Scaffold Widget
Key Takeaways
MaterialApp: Root widget for Flutter apps.
Scaffold: Provides app structure (AppBar, body, etc.).
StatefulWidget: Used when UI needs to change dynamically.
Center: Aligns child widgets to the center.
Text(): Displays text.
Flutter program Structure
Import packages
import 'package:flutter/[Link]';

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

Create Widgets
StatelessWidget: For UI that doesn’t change.
StatefulWidget: For UI that can change dynamically.
Build Method
Uses a Widget build(BuildContext context) function.
MaterialApp & Scaffold
MaterialApp: Entry point for the [Link]: Provides basic UI structure.

Syntax :

property : Widget
home: Scaffold()
appbar:AppBar()
title :Text()
body : Center()
child : Text()
Hello World Program
import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({[Link]});

@override
State<MyApp> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyApp> {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
"my first program"
),
),
body: Center(
child: Text(
"hello world"
),
),
),
);
}
}
Structure and tools
1. Project Structure in Flutter
2. The [Link] file
3. Hot Reload
4. Linter rules
5. Tree shaking and constants
1. Project Structure in Flutter : When you create a new Flutter project (flutter
create project_name), you get a well-organized structure:
Flutter Structure :
[Link]/ and ios/: These folders contain platform-specific code for each OS
and they’re automatically managed by the IDE and the compiler.
The structure is exactly the same you’d get with a new Android project on
Android Studio or iOS project on Xcode.

2. lib/: This folder is essential: it contains the Dart source code of your Flutter
app. You’re going to spend a countless amount of hours in here.

3. test/: Unit tests, widget tests and integration tests all go in this folder.

4. [Link]: This file is fundamental as it defines a Dart package and lists


dependencies of your Flutter app.
[Link]: It’s the typical markdown file you can find in any git repository.
It’s used for your git repository and at the same time as "home page" at
[Link] in case you wanted to publish a package.

Folder structure :
lib/. -> Your app’s source code goes here. Grouping files in proper folders is
essential if you don’t want to get lost in your own architecture so, before coding,
mind the structure.
– routes/
– models/
– widgets/
– [Link]
– [Link]
routes/
contains your app’s pages,

models/
is for the "business logic" and widgets/ is for reusable
UI widgets
– localizations/
– routes/
– widgets/
– models/
∗ blocs/
∗ providers/
∗ repositories/
∗ ...– [Link]
– [Link]
– localizations/
If you plan to make your apps available in multiple languages, consider
grouping all the localization logic inside localizations/.

test/.
Flutter has a powerful automated testing suite; we recommend splitting test files
according with their use case.
– unit/
– widget/
– integration/

There would be the possibility to throw all your files inside a single folder (for
example lib/) with no structure but... no! In a medium-large app architecture,
maintenance is going to be painful because there’s no logical organization
2. The [Link] file :
This file is very important and it deserves to be properly described. It gives you
control on: dependencies used by Flutter, resources/assets of your app and
the versioning system for production binaries.

YAML is a data-serialization language commonly used for configuration files. It


exposes a series of settings in a human-readable way; it has no punctuation as
it relies on indentation and line breaks.

Version : Any package is required to specify a version number which


increments at any release;
When you’re releasing an app for the Google Play store or the Apple App store, this
number is used to assign a version value to the product. For example if you had...
version: 1.1.0+5
... it would mean that your app’s version name would be 1.1.0 and the build number
would be 4. In the Android world, inside [Link], the field versionName would be
1.1.0 and versionCode would be 5.

sdk. : This section contains the constraints indicating which SDK versions your app sup
ports. The Dart team recommends to always include a lower and an upper bound but
you
could simply use ">= 2.7" and it’d be valid anyway.
environment:
sdk: ">=2.7.0 <3.0.0"
With the above range you can use everything coming from version 2.7 onward so Dart
extensions for example (introduced in 2.7) are supported.
uses-material-design : Ensures that your Flutter app is able to use icons from
the Google Material design 3 project. They are pretty common in the Google
world, especially in Android as they’re the default icons being used in many apps.

Having uses-material-design: true icons are already available, you’ve nothing to


download or setup because they’re bundled in the Flutter SDK. Icons are actually
vectorial images so they resize without quality loss
dependencies. : This is probably the most important label because it declares
any package the app is going to depend on. You just need to go to
[Link] look for a package and add a new line

dependencies:
flutter:
sdk: flutter

http: ^0.12.2
provider: ^4.3.2+2
flutter_svg: ^0.18.1

On the left there’s the name of the package while on the right there’s the
version being downloaded from the repository. They have been added in this
very simple way:
1. open [Link]
2. search for "http" or any other meaningful keyword;
3. choose a package from the list and click on the Installing tab;
4. copy/paste the given installation string, in our case "http: ^0.12.2“

assets. : This label specifies the paths to static resources your app will use such as
images,SVG vectorials, audio/video files or simple text. For example, you could create
a folder called images/ and put everything in there without having to list files one by
one.
flutter:
assets:
- images/
- files/text/[Link]
- audio/
In the second line we have imported a text file giving the exact location. The root of the
project is the directory in which you have the [Link] file. When you declare any
kind of asset, the starting point for the path is the root.
fonts : By convention this label is put at the bottom of the file, after assets. You can
download font files from [Link] and import them directly in your app.

flutter:
assets:
- images/
fonts:
- family: Roboto
fonts:
- asset: fonts/[Link]
- asset: fonts/[Link]
style: italic
- family: RobotoMono
fonts:
- asset: fonts/[Link]
weight: 400
Once you’ve downloaded the .ttf files from Google Font, create a folder called (by
convention) fonts/ and put the files in there. There’s nothing more to do because
Flutter will take care of automatically loading them.
– [Link]
Text(
'This is Google Fonts',
// Download 'pacific' and cache it
style: [Link](),
),
However, you could download font files anyway and include them as assets because
it’s faster and more secure.
flutter:
assets:
- images/
- fonts/
3. Hot Reload
fact that any edit to an .html file can be seen immediately clicking the refresh
button of the browser. It’s literally a matter of seconds because you just need
to save the file and press F5. Flutter works in the same way.

Thanks to the hot reload feature, we can refresh the UI in your emulator (or
physical device) while writing Dart code. There is no need to make a build
every time and wait for gradle/Xcode to complete.

Hot reload is blazing fast as it takes less than a second to refresh the UI.

It increases a lot the productivity because changes are immediately applied


and ready to be tested, no need to wait for build processes.
Hot reload works in most of the cases but in certain circumstances you have
to stop and re-run the app entirely:

• when you make changes to the initState() method


• when you change the definition of a class into an enum and vice versa,
• when you make changes to static fields in classes,
• when you make changes to code inside void main() {
}

In debug mode Flutter uses the JIT compilation model that, in combination with
the Dart Virtual Machine, allows fast injection of the source code and quick
incremental rebuilds. In other words, we can say that "Flutter’s hot reload is
super fast!".
4. Linter rules
A linter is a very helpful tool that reads the source code and spots syntax errors,
suspicious constructs, styling errors and much more.
By default Dart’s linter is very permissive and it marks something as error only
when really needed.

Making the linter more severe is very productive as it can discover problems and
potential bugs even before executing the code.
In order to do this there’s the need to create a file called analysis_options.yaml
in the same folder as the pubspec.
• error: causes static analysis to fail;
• warning: static analysis doesn’t fail unless warnings are treated as errors by
the analyzer;
• info: just an message info which doesn’t make static analysis fail;
• ignore: ignores the given rule
5. Tree shaking and constants
Using import "package:flutter/[Link]" might be very useful while
developing and debugging Flutter apps. It exposes three constant boolean
values the developer can use to execute a series of instructions according with
the build mode:
When building a Flutter app (in any mode), "tree shaking" is automatically
performed. It’s basically the compiler removing dead code depending on
variables being constant or not plus other factors.

The Run button of Android Studio and VS Code builds the app in debug mode
so the above code will always return "Demo".
The other statement (return _real();) is automatically removed by the compiler
because it will never be reached.
According with the build mode, after the compilation the same piece of code
can look like this:
Widgets and State
In Flutter everything that appears on the screen is called "widget" because,
technically speaking, it’s a descendant of the Widget class.
When you create user interfaces in Flutter you make a composition of widgets
by nesting them one inside the other.

If we refer to buttons, text fields, animations, containers and even the UI page
itself. Anything appearing on the screen or interacting with it is a widget.
Widgets everywhere!
Basic Structure of Widgets
Program for basic widget structure
Basic Widgets
[Link] widget : The Text widget is used to display a piece of text on the screen.
It’s highly customizable as you can change the color, the font using font assets
or the Google Font package and much more.
It just requires a string as a parameter, which is the text being displayed on the
UI, and the styling is made with the TextStyle() class. It defines many properties
of the text itself and it’s also the place in which the google_fonts package can be
used.
Row Widget
This widget places one or more children in the horizontal axis with the given
space constraints. It’s used very often when you need to have multiple items
aligned side by side. There is no const constructor for Row but you can assign it,
when possible, to the children value

there will be three Text widgets side by side at the center of the screen. By
default, a row tries to totally cover the available horizontal space; you can make
sure it shrinks to fit the width of its content using
Start : Places the items at the beginning of the row.
Column : This widget places one or more children in the vertical axis with the
given space constraints. A Column is the opposite of a Row as it has the same
purpose but it works in the opposite direction (vertical rather than horizontal).

Column( mainAxisSize: [Link], ),


A column does NOT have a scroll behavior so if there’s not enough space, you’ll get an overflow error at runtime
ListView : A ListView is basically a Column with scrolling behavior as it places
one or more children in the vertical axis, in sequence. This widget is very widely
used because it provides the possibility to scroll contents when they are bigger
than the screen size.

Widgets are aligned to the top and the scrolling direction is vertical by default but of course you can change it.
With scrollDirection you can decide whether the list has to scroll in the horizontal or vertical axis

ListView( scrollDirection: [Link], ),


The [Link](...) named constructor is very useful when the list has to be built based on an existing collection
Container :
This widget is the equivalent of a <div></div> tag in the HTML world; it’s a
general purpose container you can use to customize painting, positioning, sizing
and much more.
The rotation is obtained thanks to transform: [Link](-0.25), which
defines how to place an object in the 3D space.
LinearGradient: a progressive transition of two or more colors along a straight
line.
RadialGradient: a progressive transition of two or more colors radiating around
a central point.
SweepGradient: a progressive transition of two or more colors with a circular
sweep on a central point.

can also have rounded borders with borderRadius: [Link](30.0)


or a simple plain background color with the color: property
Stack and Positioned
Thanks to the Stack widget you can overlap widgets and freely position them
on the screen using Positioned.
Even if children are placed outside the bounds of the UI, no overflow errors will
appear because a Stack doesn’t constrain the bounds of width and height.
The UI is created with a red box and the Text widget is painted in front of the Container. The order in which you place the
widgets really matters because children at the bottom of the list are placed, relatively, in front of the ones at the top.
The foreground widget goes at the end of the list.
In this case the red box would be placed in front of the Text widget because, in
order, it comes after and thus "Hello" is not visible because covered by the
Container. You could however decide to move the text at a specific position of
the screen:
Stateless and Stateful widgets
A class becomes a Flutter widget when it subclasses StatelessWidget or
StatefulWidget and overrides the Widget build(...); abstract method. That’s it:
The main task of a widget is laying out other widgets on the tree using the
build() method.

Stateless widget. : Use this kind of widget


1. when you need to create a piece of UI that is not going to change over the
time.
2. It’s a "standalone" block that doesn’t depend on external events or
sources.
3. it just relies on its constructor and the internal data.
Key Features :
1. A StatelessWidget does not change once it is built.
2. It only depends on the input parameters and does not have an internal state.
3. Used for UI elements that do not require real-time updates.
4. setState() will not be there.
5. Since this class is immutable it’s a very good idea marking the instance
variables as final so that a const constructor can be declared.

When to use:
1. Static UI elements like labels, buttons, and icons.
2. When data doesn’t change after the widget is built.
This is a perfect example of a StatelessWidget because the contents will always
be the same;
no external dependencies or streams are going to change the text or the icon.
Once created, the widget is "static" because it will never change: it’s a "solid
block".
By convention Flutter widgets have named optional parameters in the
constructor;
in case they were required, use the required keyword.

Even if the class takes a string from the outside, via constructor, it still doesn’t
change over the time. The given name will always be the same and thus
the widget will never change/rebuild, so a stateless solution is fine
Stateful widget.
Use this kind of widget when you need to create a piece of UI that is going to
change over the time.
In this case the UI is going to dynamically change due to external events such as
the received response of an HTTP request or the callback triggered by a button
tap.

In this widget the main actor is the IconButton: once tapped by the user, the
onPressed callback is triggered and the _counter variable is incremented.
Key Features :
1. The StatefulWidget itself (immutable).
2. The State class (mutable) where all changes happen.
3. Used for UI elements that need to update when data changes.
4. setState() will be used.

When to use:
1. When UI needs to update dynamically (e.g., counters, forms, animations).
2. Widgets that rely on user interactions or real-time data update.
1. Counter is the widget itself and thus it’s inserted in the widget tree; _CounterState is
the mutable state of the Counter widget. When Flutter rebuilds the widget tree to
refresh the UI, the build(...) method of State<T> is called.
2. This is the standard pattern for the creation of a stateful widget and you should
really follow it. Both Android Studio and VS Code can automatically create the
boilerplate for you.
3. Subclasses of State<T> gain access to the setState(...) method which rebuilds the
widget (it’s like a refreshing tool).
4. Member instances, such as _counter, survive to rebuilds. Only what’s inside the
build() method is refreshed.

When you tap on the button, the onPressed callback is activated: setState(...) executes
its body and then Flutter rebuilds the widget. In our example, int _counter gets incre
mented by 1 and then the widget is refreshed so that Text can display the new updated
value
Rebuilds and optimization
The framework traverses the widget tree very often. The build() method is
called, for sure, the first time the UI is rendered. It will be called more than once
during your app’s lifetime but you can’t predict how many times because lots of
factors can trigger a re-build:
• calling setState,
• rotating the screen of the device,
• awaiting the result of a future,
• listening to incoming stream events.

When we say "the framework does many rebuilds" we mean that the method
build() of a specific widget is called more than once. Because of the structure of
the widget tree, every children will be rebuilt as well because there must be
consistency along the hierarchy
How to avoid Rebuild in Flutter :
1. const constructor
2. Prefer widget composition over functions

1. const constructor
[Link] constructor :
➢ If you mark a list with const by consequence every object inside it will also be
constant.
➢Flutter builds constant widgets one time only.
➢Using const constructors on widgets is like caching them: once created, they
will never be re-built again.

If the class is allowed to have a const constructor, then it’s immutable.


It will never change over the time so Flutter doesn’t have to rebuild it more
than once.
A constant constructor on a big subtree can save a lot of computational time.
Try to use const constructors as much as possible because the build method of a
constant widgets is executed only once (at the time of the creation). Any
subsequent re-build will simply ignore every widget whose constructor have
been marked with const.
class ExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {.}
}
In this case there isn’t a constant constructor and thus the widget cannot be
inserted in the tree using const ExampleWidget().
Stateful widgets can have a const constructor too of course:
[Link] widget composition over functions
It’s common knowledge that code duplication is bad and so you’ll create very
often reusable widgets. For example, many apps have a "footer" which
includes icons and a bit of text about the copyrights.
To make FooterWidget stateless because it’s a reusable block of code that
doesn’t change its state and it’s not influenced by external events. It lives on
its own and it can be reused in many different pages to show a footer at the
bottom.

there is a constant constructor because the class has no mutable variables;


• in Column we can’t use children: const [...] because Row does not define a
constant constructor. Nevertheless, we can manually put const in the single
child inside, where possible.
By using stateful

It’s a function returning the Column widget with its children: you should absolutely NEVER
prefer functions over widgets because:
1. Functions of course doesn’t have const constructors.
2. Flutter is forced to rebuild widgets returned by a function every time
because it knows nothing about them (no BuildContext is provided).
3. Classes are leaves of the widget tree but functions aren’t and thus there’s no
BuildContext available.
Widgets can be cached thanks to const constructors; functions can NOT be
cached and thus they’re executed every time. You should (or actually... must!)
always rely on reusable widgets rather than functions.

You might also like