Mastering Flutter Mastering Computer Science
Mastering Flutter Mastering Computer Science
Mastering Flutter helps the reader master the popular Flutter framework for
rapid cross-platform app development.
The best part about Flutter is that you can use it to create apps for iOS,
Android, desktop, and the web, all with the same codebase. Flutter comes
with a widget-based UI library, a collection of UI elements (text boxes,
picture blocks, buttons, and so on) that can be used to customize and
construct apps. Consider Flutter to be the app’s frontend user interface and
Dart to be the backend code that is generated automatically.
Edited by
Sufyan bin Uzayr
First Edition published 2023
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
Reasonable efforts have been made to publish reliable data and information, but the author and
publisher cannot assume responsibility for the validity of all materials or the consequences of their
use. The authors and publishers have attempted to trace the copyright holders of all material
reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let
us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information
storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access
www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive,
Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact
[email protected]
Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
Preface
About the Author
FUNCTION IN DART
Function Benefits
Function Defining
Calling a Function
Passing Arguments to the Function
Return a Value from the Function
Function Examples
Dart Function with an Argument and a Return Value
Dart Function with No Parameter and Return Value
Dart Function with No Parameter and without a
Return Value
Dart Function with Parameter and without a Return
Value
ANONYMOUS FUNCTION IN DART
Lexical Scope
Lexical Closure
THE MAIN() FUNCTION
Return Value in Dart
Dart Value with Return Value
WHAT IS RECURSION?
What Is Base Condition in Recursion?
Recursive Function in Dart
How Does Recursion Work?
Recursive Function Qualities
OBJECT-ORIENTED CONCEPTS IN DART
Class
Object
Inheritance
Polymorphism
Interfaces
Abstract Class
DART CLASSES AND OBJECT
Defining a Class in Dart
Object in Dart
Creating Class Objects in Dart
Assessing Instance Variable and Function
The Advantages of Objects
WHAT EXACTLY IS CONSTRUCTOR?
Creating Constructor
Types of Constructors
Default Constructor or No-Argument Constructor
Parameterized Constructor
Named Constructors
THIS KEYWORD IN DART
Local Variables
Class Variable
Instance Variable
The Difference between Class Variable and Instance Variable
STATIC KEYWORD IN DART
Static Variable in Dart
Static Variable Declaring
Accessing the Static Variable
Static Method
Static Methods Declaration
Static Method Calling
SUPER KEYWORD
The Use of a Static Keyword
Using a Super Keyword with Variables
Using the Super Keyword with the Parent Class Method
Using a Super Keyword with the Constructor
INHERITANCE IN DART
Inheritance Types
Single Level Inheritance
Multilevel Inheritance
Hierarchical Inheritance
SUPER CONSTRUCTOR IN DART
Implicit Super
Explicit Super
METHODS IN DART
Instance Methods
Creating Instance Methods
Calling the Instance Method
Class Methods
Creating Class Methods
Calling the Class Method
METHOD OVERRIDING IN DART
What Exactly Is Polymorphism?
Example of Method Overriding
Method Overriding Using the Super Keyword
The Benefit of Method Overriding
Rules of Method Overriding in Dart
GETTERS AND SETTERS IN DART
Defining a Getter
Defining a Setter
ABSTRACT CLASSES IN DART
Rules for the Abstract Classes
Declaring the Abstract Class
Abstract Class Usage
DART INTERFACES
Declaring an Interface
Implementing an Interface
Implementing Multiple Inheritance
Rules for Implementing Interfaces
CHAPTER SUMMARY
DART EXCEPTIONS
The Try/On/Catch Blocks
Finally Block
Throwing an Exception
Custom Exceptions
TYPEDEF IN DART
Declaring a Typedef
Assigning the Typedef Variable
Calling Function with Typedef
Complete the Program by Using Typedef
Typedef as Parameter
Debugging in Dart
What Exactly Are Breakpoints?
How Do I Create Breakpoints in WebStorm?
METADATA IN DART
Creating the Metadata Annotation
COLLECTION IN DART
Collections Iteration
HashMap <K, V Class>
DART GENERICS
Generic Map
PACKAGES IN DART
Package Manager in Dart
Read XML String
LIBRARIES IN DART
Importing a Library
Importing and Using a Library as an Example
Library Encapsulation
Creating Custom Libraries (User-Defined Library)
Step 1: Library Declaration
Step 2: Library Connecting
Custom Library as an Example
Name Alias of Library
GENERATORS IN DART
Synchronous Generator
Asynchronous Generators
The Yield Keyword
The Sync* Keyword
The Async* Keyword
DART CALLABLE CLASSES
DART ISOLATES
Create and Start an Isolate
Stop an Isolate
Complete Program
ASYNC IN DART
Difference between Synchronous and Asynchronous
Dart Future
Dart Async and Await
Dart Await Keyword
What Exactly Is Concurrency?
How Does One Achieve Concurrency?
What Is Unit Testing?
Unit Testing Task
Advantages of Unit Testing
Dart Unit Testing
Group of Test Cases
Grouping Test Cases
DART HTML DOM
Finding the DOM Elements
Event Handling
CHAPTER SUMMARY
APPRAISAL
BIBLIOGRAPHY
INDEX
Preface
Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a decade of
experience in the industry. He has authored several books in the past,
pertaining to a diverse range of topics, ranging from History to
Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT company
specializing in EdTech solutions. He also runs Zeba Academy, an online
learning and teaching vertical with a focus on STEM fields.
Sufyan specializes in a wide variety of technologies such as JavaScript,
Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees,
including ones in Management, IT, Literature, and Political Science.
Sufyan is a digital nomad, dividing his time between four countries. He
has lived and taught in universities and educational institutions around the
globe. Sufyan takes a keen interest in technology, politics, literature,
history, and sports, and in his spare time, he enjoys teaching coding and
English to young students.
Learn more at sufyanism.com
CHAPTER 1
Getting Started with Flutter and Dart
DOI: 10.1201/9781003299363-1
IN THIS CHAPTER
Introduction to Fart
Introduction to Flutter
Variables and data types
Nullable and Non-nullable types
Data type operators
Only by making a place in our mobile device can mobile app development emphasize our brand name. The more it
reaches out to the public, the better our reputation will be.
Creating a profitable application now necessitates the selection of the appropriate app development framework.
A framework that allows for rapid app development while not making it too expensive to invest in.
Flutter and Dart are two app development technologies that can meet your requirements. We may compare the
features and benefits of both frameworks and then make an informed decision on which framework would best suit
our app concept.
Flutter’s Features
It is a simple technique for creating gorgeous mobile and desktop apps with a complete collection of material
designs and widgets. This section will go over its primary features for constructing the mobile framework.
Open-source: Flutter is a free and open-source mobile application development framework.
Cross-platform: This capability enables Flutter to write code once, maintain it, and execute it on several
platforms. It saves developers’ time, effort, and money.
Hot Reload: When the developer changes the code, the changes are visible instantly, thanks to Hot Reload. It
implies that the modifications are immediately displayed in the app. It is a highly useful feature that helps the
developer to correct errors immediately.
Accessible Native Features and SDKs: This feature makes app creation simple and enjoyable by utilizing
Flutter’s native code, third-party integration, and platform APIs. As a result, we have simple access to both
systems’ SDKs.
Minimal Code: The Flutter app is written in the Dart programming language, which employs JIT (Just-in-
Time) and AOT (Ahead-of-Time) compilation to increase total start-up time, functionality, and speed. JIT
improves the development system and refreshes the UI without requiring additional work to create a new one.
Widgets: The Flutter framework includes widgets, which may use to create unique, customizable designs.
Most notably, Flutter has two sets of widgets: Material Design widgets and Cupertino widgets, which aid in
providing a bug-free experience across all platforms.
Flutter Advantages
Flutter’s advantage is that it meets the specific demands and criteria for designing mobile applications. It also has
several benefits, which are stated as follows:
Because of the hot-reload functionality, it speeds up the app development process significantly. This
functionality allows us to edit or update the code, and the changes are reflected as soon as they are made.
It enables smoother and more fluid app scrolling experiences with fewer hangs or cuts, allowing apps to run
faster in contrast to competing mobile app development frameworks.
Flutter minimizes testing time and effort. Because flutter apps are cross-platform, testers do not necessarily
need to conduct the same set of tests on multiple platforms for the same app.
It offers a fantastic user experience using a design-centric widget, powerful APIs, and many other features.
It is comparable to a reactive framework in that developers do not need to change the UI content manually.
Because of its quick development time and cross-platform nature, it is ideal for MVP apps.
Flutter’s History
Google’s Flutter is a free and open-source UI software development kit. It’s used to develop apps for Android,
iOS, Windows, and the web. The initial version of Flutter was revealed at the Dart Developer Summit in 2015. It
was initially known as the “Sky” codename and is compatible with the Android operating system. In May 2017,
the first Flutter Alpha version (v-0.06) was published after the launch of Flutter.
Later, in September 2018, at the keynote of Google Developer Days in Shanghai, Google published the second
preview of Flutter, which was the last major release before the Flutter 1.0 version. At the Flutter Live event on
December 4, 2018, the first stable version of the Flutter framework, denoted as Flutter 1.0, was published. On
October 24, 2019, the framework’s current stable release was Flutter v1.9.1+hotfix.6.
Prerequisites
Before diving into Flutter, you should have a solid grasp of Dart programming, Android Studio, and web scripting
languages like HTML, JavaScript, and CSS.
Audience
We created this lesson for both novices and pros that wish to establish a career around Flutter or understand the
fundamentals of Flutter quickly. There are several topics accessible to assist you master Flutter technology quickly.
Problems
We guarantee that our Flutter lesson will not cause us any problems. However, please let us know if we discover
an error in the comments area.
INSTALLATION OF FLUTTER
This part describes about how to set up an environment for effective Flutter application development.
Install Git
Step 1: Go to https://git-scm.com/download/win to get Git.
Step 2: To complete the installation, run the.exe file. Ensure that you have picked the preferred option during
installation.
Step 4.1: Navigate to MyComputer Properties > Advanced > Environment Variables. The screen will
appear.
Step 4.2: Next, choose the path and then click on modify. The screen appears.
Step 4.3: In the preceding window, click New->write path of Flutter bin folder in variable value -> ok ->
ok -> ok -> ok.
Step 5: Finally, execute the $ flutter doctor command. This tool checks for all Flutter app development
prerequisites and reports on the state of our Flutter installation.$ flutter doctor
Step 6: When we run the above command, the system will analyze, and a report will display, as seen in the
image below. Here we will discover information on all missing tools needed to execute Flutter and
development tools that are available but not linked to the device.
Step 7: Download and install the Android SDK https://developer.android.com/studio. If the flutter doctor
command fails to locate the Android SDK tool, we must first install the Android Studio IDE. Follow the
instructions given below to install Android Studio IDE.
Step 7.1: Get the most recent Android Studio executable or zip file from the official site.
Step 7.2: Double-click the.exe file to launch it once the download is complete. The following dialogue
box will appear.
Step 7.3: Follow the installation wizard’s instructions, when the installation wizard is finished.
Step 7.4: On the previous screen, select Next-> Finish. After clicking the Finish button, select the
“Don’t import Settings” option and click OK. It will launch Android Studio.
Step 8: Next, you must install an Android emulator. It’s in charge of executing and testing the Flutter
application.
Step 8.1: To create an Android emulator, navigate Android Studio > Tools > Android > AVD Manager
and select Create Virtual Device. Alternatively, go to Help->Find Action->Enter Emulator in the search
box. The screen will appear.
Step 8.2: Select our device definition and press the Next button.
Step 8.3: Click next after selecting the system image for the most recent Android version.
Step 8.4: Now, double-check the entire AVD setup. If everything is correct, click Finish. The screen
appears.
Step 8.5: Finally, click on the icon pointing inside the red rectangle. The Android emulator was shown.
Step 9: Install the Flutter and Dart plugins to construct a Flutter application in Android Studio. These plugins
provide a template for creating a Flutter application and executing and debugging Flutter applications within
Android Studio. To install these plugins, follow the steps given below.
Step 5: Finally, execute the $ flutter doctor command. This tool checks for all Flutter app development
prerequisites and reports on the state of our Flutter installation.
$ flutter doctor
Step 6: When we execute the command mentioned above, it will assess the system and provide data on any
missing tools necessary to run Flutter and any development tools that are present but not linked to the device.
Step 7: If the Flutter doctor tool indicates that we need to update our Xcode tools, do so.
Step 8: If the Flutter doctor tool indicates that you need to update our Android Studio and SDK, do so.
Step 9: To design an iOS application, we must either set up an iOS emulator or connect an iPhone device to
the system.
Step 10: Install an android emulator or connect an android device to the system once more to construct an
android application.
Step 11: Install the Flutter and Dart plugins to construct a Flutter application in Android Studio. These
plugins provide a template for creating a Flutter application and executing and debugging Flutter applications
within Android Studio.
void main() {
for (int x = 0; x < 5; x++) {
print('helloo ${x + 1}');
}
}
Dart is a client-optimized programming language for creating quick apps on any platform. Its purpose is to provide
the most productive programming language for cross-platform development and a flexible execution runtime
platform for app frameworks.
Languages are characterized by their technical envelope, the decisions made during development that form a
language’s capabilities and strengths. Dart is built for a technical envelope ideal for client development, focusing
on development (sub-second stateful Hot Reload) and high-quality production experiences across a wide range of
compilation targets (web, mobile, and desktop).
Dart is also the basis for Flutter. Dart offers the language and runtimes that power Flutter apps, but it also helps
with many essential development responsibilities, including code formatting, analysis, and testing.
Dart: Language
Dart is type safe; it employs static-type checking to verify that a variable’s value always matches the static type of
the variable. This is sometimes referred to as sound typing. Although types are required, type annotations are not
required due to type inference. Dart’s typing system is very versatile, enabling the usage of a dynamic type in
conjunction with runtime checks, which can be beneficial during experimentation or for work that requires a high
degree of dynamicity.
Dart has good null safety, which means that values can’t be null until we explicitly state they can. Dart’s sound
null safety protects us from null exceptions at runtime via static code inspection. Unlike many other null-safe
languages, when Dart concludes that a variable is non-nullable, it stays that way. If we examine our running code
in the debugger, we’ll notice that non-nullability is preserved at runtime.
The following code example demonstrates numerous Dart language capabilities, including libraries, async calls,
nullable and non-nullable types, arrow syntax, generators, streams, and getters. See the samples page for examples
of how to use other Dart capabilities.
Characteristics of Dart
Dart is a powerful object-oriented, open-source programming language with many helpful features. It is a new
programming language that includes various programming utilities such as interfaces, collections, classes,
dynamic, and optional typing. It is designed for both the server and the browser. The following is a list of the
essential Dart features.
Features of Dart.
Open Source
Dart is an open source programming language, which is free to use. Google created it, is compliant with the
ECMA standard, and is licensed under the BSD license.
Platform Independent
Dart is platform-independent, supporting all major operating systems such as Windows, Linux, and Macintosh.
Dart has its Virtual Machine (VM), known as the Dart VM, which allows us to run Dart code on any operating
system.
Object-Oriented
Dart is an object oriented programming language that supports all oops concepts, including classes, inheritance,
interfaces, and optional typing. It also supports advanced ideas such as mixin, abstract, classes, reified generic, and
a robust type system.
Concurrency
Dart is an asynchronous programming language that allows multithreading through Isolates. Isolates are
independent entities tied to threads but do not share memory and communicate across processes via message
passing. To ensure successful communication, the message should be serialized. The message is serialized by
utilizing a snapshot created by the provided object and then transmitted to isolation for destabilization.
Extensive Libraries
Dart has numerous important inbuilt libraries such as SDK (Software Development Kit), core, math, async,
convert, html, IO, and so on. It also allows us to structure our Dart code into libraries with correct namespacing.
The import statement will enable it to be reused.
Easy to Learn
As we established in the last part, learning Dart is not a Hercules task because its syntax is similar to Java, C#,
JavaScript, kotlin, and other programming languages. If we know any of these languages, we can learn Dart
quickly.
Flexible Compilation
Dart allows us to compile code in various ways that are both flexible and quick. It supports two compilation
processes: AOT and JIT. The Dart code is sent in another language that contemporary web-brewers can execute.
Type Safe
Dart is a type-safe language, which implies that it utilizes both static type checking and runtime checks to ensure
that a variable’s value always matches the variable’s static type, also known as sound typing.
Type annotations are optional due to type interference, even if types are necessary. This improves the readability
of the code. Another advantage of using a type-safe language is that when we alter a code section, the system alerts
us about the previous update.
Objects
The Dart considers everything to be an item. An object is a value that is assigned to the variable. Dart also
considers functions, integers, and texts to be objects. All objects derive from the Object class.
Browser Support
The Dart supports all recent web browsers. It includes the dart2js compiler, which translates Dart code into
efficient JavaScript code suited for all types of web browsers.
Community
Dart has a sizable global community. So, if we have difficulty when coding, we may efficiently locate assistance.
The devoted development team is working hard to improve its functioning.
Dart’s Libraries
Dart includes a robust set of core libraries that provide the foundation for many common programming tasks:
Dart programs provide built-in types, collections, and other essential features (dart:core)
Queues, linked lists, hashmaps, and binary trees are more complex collection types (dart:collection)
Encoders and decoders for transforming data representations such as JSON and UTF-8 (dart:convert)
Random number creation and mathematical constants and functions (dart:math)
Non-web apps can use file, socket, HTTP, and other I/O methods (dart:io)
Asynchronous programming is supported by classes such as Future and Stream (dart:async)
Lists that handle fixed-sized data effectively (for example, unsigned 8-byte integers) and SIMD numeric types
(dart:typed data)
Foreign function interfaces are used to interoperate with other code that uses a C-style interface (dart:ffi)
Concurrent programming using isolates – autonomous workers that are comparable to threads but do not
share memory and communicate exclusively via messages (dart:isolate)
HTML elements and other resources for web-based applications that must communicate with browsers and
the Document Object Model (DOM) (dart:html)
Aside from the core libraries, many APIs are available through a diverse range of packages. Dart’s team releases a
plethora of useful supplemental packages, such as these:
characters
intl
markdown
http
crypto
Furthermore, third-party publishers and the greater community publish thousands of packages with support for
features like these.
XML
Windows integration
compression
SQLite
Dart: Platforms
Dart’s compiler technology allows us to run code in a variety of ways:
Dart contains a Dart VM with JIT compilation and an AOT compiler for creating machine code for programs
targeting mobile and desktop platforms.
Dart contains a development time compiler (dartdevc) and a production time compiler for web-targeted
programs (dart2js). Dart is translated into JavaScript by both compilers.
The Flutter framework is a popular multi-platform UI toolkit driven by the Dart platform that provides tools and
UI frameworks for creating UI experiences that operate on iOS, Android, macOS, Windows, Linux, and the web.
Dart’s Runtime
Regardless of the platform or how your code is compiled or running, it requires a Dart runtime. This runtime is in
charge of the critical tasks listed as follows:
Dart employs a managed memory model in which unused memory is recovered by a GC.
Enforcing the Dart type system: While most Dart type tests are static (compile-time), others are dynamic
(runtime). The Dart runtime, for example, enforces dynamic checks via type check and cast operators.
Managing isolates: The Dart runtime is in charge of the primary isolate (where code generally executes) and
any other isolates created by the app.
The Dart runtime is automatically included into self-contained executables on native systems, and it is part of
the Dart VM given via the dart run command.
// Define function.
void printInteger(int aNumbers) {
print('The number is $aNumbers.'); // Print to console.
}
// This is where app starts executing.
void main() {
var numbers = 52; // Declare and initialize variable.
printInteger(numbers); // Call function.
}
This application employs the following technique, which is applicable to all (or almost all) Dart apps:
// This is a comment: A single-line comment. Dart also allows for multiline comments and document
comments.
void: A special type that represents a value that will never be utilized. The void return type is used by
functions that do not explicitly return a value such as printInteger() and main().
int: Another type that denotes an integer. String, List, and bool are among more built-in types (52).
A literal number: Number literals function as a type of compile-time constant.
print(): It is a convenient method for displaying output.
‘…’ (or “…”): A string literal.
$variableName (or $expression): String interpolation: including the string equivalent of a variable or
expression within a string literal.
main(): A unique, mandatory top-level function that initiates program execution.
var: A variable declaration without identifying its type. The initial value of this variable (int) determines its
type (int) (52).
Key Actions
Keep the following facts and concepts in mind while we study the Dart language:
Everything we put in a variable is an object, and every object is a class instance. Objects include integers,
functions, and null. All objects, with the exception of null (if sound null safety is enabled), derive from the
Object class.
Dart is tightly typed, yet type annotations are not required since Dart can infer types. The code above assumes
that the number is of type int.
If we activate null safety, variables cannot contain null unless you explicitly specify that they may. By
appending question mark (?) to the end of a variable’s type, it can be made nullable. A variable of type int ? ,
for example, might be an integer or null. If you know an expression never evaluates to null, but Dart
disagrees, we may add ! to assert that it isn’t null (and to throw an exception if it is). In this case, int a =
nullableButNotNullInt.
When we wish to explicitly declare that any type is acceptable, use the type Object? (if null safety is enabled),
Object or type checking must be deferred until the special type dynamic runtime.
Dart supports generic types such as Listint> (a list of integers) and ListObject> (a list of objects) (a list of
objects of any type).
Dart allows both top-level functions (such as main()) and functions that are attached to a class or object (static
and instance methods, respectively). Functions within functions can also create (nested or local functions).
Dart, too, provides top-level variables and variables associated with a class or object (static and instance
variables). Instance variables are also referred to as fields or properties.
Dart, unlike Java, lacks the keywords public, protected, and private. If an identifier begins with an underscore
(_), it is reserved for its library.
Identifiers can begin with a letter or an underscore (_), including any combination of those characters and
numerals.
Dart supports expressions (which contain runtime values) and statements (which do not). For instance,
consider the conditional expression condition ? expr1: expr2 is either expr1 or expr2. In comparison, an if-
else sentence has no utility. A statement frequently comprises one or more expressions, but an expression
cannot contain a statement directly.
Dart tools can provide two types of faults and warnings. Warnings are just signals that our code may not
function properly, but they do not prohibit our application from running. Errors can occur at either the build
or execution time. A compile-time error stops the code from running at all; a runtime problem causes an
exception to be thrown while the code is running.
Variables
Here’s an example of generating and initializing a variable:
Variables keep track of references. The variable name has a reference to a String object with the value “Bobby.”
The name variable’s type is inferred to be String, but we can alter it by specifying it. Specify the Object type if
an object is not bound to a single type (or dynamic if necessary).
Default Value
Uninitialized variables of the nullable type have a null value as their default value. (If we haven’t enabled null
safety, each variable has a nullable type.) Because numbers, like everything else in Dart, are objects, variables with
numeric types are initially null.
int? lineCounts;
assert(lineCounts == null);
If we enable null safety, we must first initialize the values of non-nullable variables:
int lineCounts = 0;
A local variable does not have to be initialized when it is declared, but it must be assigned a value before it may be
used. For example, the following code is valid since Dart can detect that lineCounts is not null when it is supplied
to print():
int lineCounts;
if (weLikeToCount) {
lineCounts = countLines();
} else {
lineCounts = 0;
}
print(lineCounts);
Top-level and class variables are initialized lazily; the initialization code is executed the first time the variable is
used.
INSTALLATION OF DART
We must first install the Dart programming environment on our local system to study Dart. The following
instructions describe installing the Dart SDK (Software Development Kit) on various operating systems.
Step 2: Type the following command to install the Dart SDK using the apt-get option in the terminal.
export PATH="$PATH:/usr/lib/dart/bin"
To modify the PATH for upcoming terminal sessions, use the following command:
Step 2: Run the following command to see which version we have installed.
main(): The main() function signifies that we are starting our program. It is a crucial function that
initiates the program’s execution.
print(): This function prints the output to the console. It’s comparable to C, JavaScript, or any other
programming language. Curly brackets and semicolons are required for proper usage.
Step 3: Launch the command line and compile the program. By executing dart hellooworld.dart, we may
launch the Dart program. The screen will display Helloo World.
Running on Browser
Dart includes an online editor known as DartPad, which may be found at https://dartpad.dartlang.org/. We may
write the code on the left side of the screen, and the output appears on the right. With the Dart Code, we can add
HTML and CSS. Dart also includes several sample programs that may use to learn the language.
Using IDE
Dart is supported by a number of IDEs, including Visual Studio Code, WebStorm, IntelliJ, and others. Download
the dart extension and execute the code to get the visual studio code.
Dart Identifiers
An identifier is a name used to declare variables, methods, classes, and functions, among other things. An
identifier is a string of letters ([A to Z], [a to z]), digits ([0–9]), and underscore (_), with the first character not
being a number. A few guidelines for defining IDs are as follows:
A digit should not be used as the initial character.
Special characters are not permitted except for the underscore (_) and the dollar symbol ($).
Two underscores (__) in a row are not permitted.
The initial character must be an alphabetic letter (uppercase or lowercase) or an underscore.
Identifiers must be one-of-a-kind and cannot include any whitespace.
They take instance into account. The variables Joseph and joseph will be handled differently.
The following table contains a list of valid and incorrect identifiers.
Valid Identifiers Invalid Identifiers
Firstnames __firstnames
firstNames first names
vari1 V5ari
$counts first-names
_firstnames 1results
First_names @vari
void main()
{
var names = "Param";
var roll_no = 25;
print("My name ${names} My roll number is ${roll_no}");
}
Dart’s Semicolon
The semicolon is used to conclude a sentence, indicating that the statement has concluded. A semicolon must use
to end each statement (;). Using a semicolon as a delimiter, we may write many statements on a single line. If the
compiler is not used correctly, it will issue an error. Here’s an example:
Block in Dart
The block is a grouping of the statements enclosed by curly braces. Curly braces are used in Dart to gather all of
the statements in a block. Consider the following syntax.
Syntax:
{ //start block
//block of statement(s)
}// end block
Command-Line Options for Dart
The Dart command-line parameters are used to affect the execution of Dart script. The following are the normal
command-line arguments.
Sr. Command-line Options Descriptions
1. -c or –c It supports assertions as well as type checks.
2. --version It displays information about the VM version.
3. --package<path> It specifies the location of the package resolution configuration file.
4. -p <path> It specifies where the libraries may be found.
5. -h or –help It is used to request help.
Checked Mode
The checked mode allows several Dart code checks such as type-checking. While developing processes, it alerts or
throws errors. To activate the checked mode, type -c or – checked before the name of the dart script-file on the
command prompt. The Dart VM operates in checked mode by default.
Production Mode
The Dart script is now in production mode. It ensures that performance will improve while the script is executing.
Consider the following scenario.
void main() {
int vari = "helloo";
print(vari);
}
dart -c mode.dart
COMMENTS IN DART
The collection of statements disregarded by the Dart compiler during program execution is known as comments. It
is used to make the source code more readable. In general, comments provide a concise overview of what is
happening in the code. We can explain the operation of variables, functions, classes, or any other expression in the
code. Programmers should make advantage of the comment to improve their practice. In the Dart, there are three
categories of comments.
Comments Types
Dart supports three types of comments:
Single-line comments
Multi-line comments
Documentation comments
Single-Line Comments
We may use the // to add comments to a single line (double-slash). The single-line comments can be used till there
is a line break.
Example:
void main(){
// This will print the given
print("Welcome to Dart");
}
The Dart compiler entirely ignores the // (double-slash) command and retunes the result.
Multi-Line Comments
When we need to apply comments to many lines, we may use / *. . . .*/. The compiler ignores anything typed
inside the / *…*/; however, it cannot be nested with multiline comments. Consider the following example:
void main(){
/* This is example of multi-line comment
This will print the given */
print("Welcome to Dart");
}
Documentation Comments
Document comments are used to create documentation or reference a project/software package. It can be a single
or multiline comment beginning with /// or /*. On successive lines, we may use ///, which is the same as a multiline
comment. Except for those put inside the curly brackets, these lines are ignored by the Dart compiler. Classes,
functions, parameters, and variables can all be defined. Consider the following scenario.
///This
///is a
///example of multi
/// line comment
Example:
void main(){
///This is
///the example of a
///multiline comment
///This will print the given
print("Welcome to Dart");
}
KEYWORDS IN DART
Dart Keywords are reserved words with particular significance for the compiler. It can’t be used as a variable,
class, or function name. Keywords are case sensitive; therefore, they must type exactly as defined. The Dart
language contains 61 keywords. Some are common, and we may be familiar with some of them, while others are
unique. The following is a list of the Dart keywords.
A few keywords are indicated with a superscript in the preceding list of keywords (1, 2, and 3). Following that, we
will explain why superscript is used.
Subscript 1: These are known as contextual keywords. They have a specific meaning and are utilized in
certain areas.
Subscript 2: These are known as built-in identifiers. These keywords are used to translate JavaScript code to
Dart; they are considered legitimate identifiers but cannot be used in class names, function names, or import
prefixes.
Subscript 3: These are newly added asynchrony-related keywords.
Dart Number
The Darts Number is used to keep track of the numerical values. There are two sorts of numbers: integers and
double.
Integer: An integer value is a whole number or a non-fractional value. Integer data types provide 64-bit non-
decimal values ranging from −263 to 263. An unsigned or signed integer value can store in a variable. The
following is an example:
Double: A double value represents 64 bits of information (double precision) for a floating number or a
number with several decimal points. The double keyword is used to declare a variable of the double type.
double pi = 3.14;
Data String
A string is the character sequence. If we save data such as a name, address, special character, and so on. Either
single or double quotation marks indicate it. A Dart string is a string made up of UTF-16 code units.
Dart Boolean
The Boolean type represents true and false. The term bool is used to represent Boolean Type. The numeric
numbers 1 and 0 cannot express whether a value is true or false.
Dart Lists
The list in Dart is a collection of ordered things (value). A list is comparable to an array in concept. A collection of
several elements in a single variable is defined as an array. The list’s items are separated by a comma in a square
bracket[]. The following is an example list:
Dart Maps
The maps type is used to hold key-value pairs of values. Each key has a value associated with it. Any type of key
and value can use. The key in Map must be unique, but the value can appear several times. Curly braces {} define
the Map, and a comma separates each pair.
Dart Runes
Strings, as we know, are a sequence of Unicode UTF-16 code units. Unicode is a method for describing a unique
numeric value for each digit, letter, and symbol. Dart Runes are a unique string of Unicode UTF-32 units. It’s used
to express the unique syntax.
The special heart character (♥), for example, is identical to Unicode code u2665, where u stands for Unicode,
and the digits are hexadecimal integers. If the hex value is less than or more than four digits, it is enclosed in a
curly braces {}.
Example:
void main(){
var hearts_symbol = '\u2665';
print(hearts_symbol);
}
Dart Symbols
Dart Symbols are objects used to refer to an operator or identifier declared in a Dart program. It is typical in APIs
to refer to identifiers by name since identifier names can change but not identifier symbols.
The variable name carries the string value “Devaan” here. Variables in Dart are used to hold references. The
variable above has a reference to a String with the value Devaan.
Syntax:
var <variable_names> = <values>;
Example:
var name = 'Anie'
In the above example, the variable name has allotted some memory space. The semicolon(;) is required because it
separates one program statement from another.
Type Annotations
As previously said, the Dart is an infer language, but it also has type annotation. The type of value the variable can
store is suggested when it is declared. We include the data type as a prefix before the variable’s name in the type
annotation to ensure that the variable may hold certain data types. The syntax is shown below.
Syntax:
<type> <variable_names>;
Example:
int ages;
String msgs = "Welcome to Dart";
In the above example, we defined ages to hold the integer data. The string data was stored in the variable msgs.
Declaring the Variable as Having Multiple Values
Dart allows us to specify multiple values of the same type to variables. We can perform this in a single sentence,
with commas between each value. The syntax is shown below.
Syntax:
<type> <var1,var2....varN>;
Example:
int a,b,c;
Default Value
When a variable is declared but not initialized, the Dart compiler assigns a default value (Null). Even the numeric
type variables are allocated a null value at first. Consider the following scenario.
int counts;
assert(counts == null);
The const keyword is used to define compile-time constants. We can assign a value to a compile-time constant
such as a number, string literal, const variable, and so on.
const b = 2000;
The const keyword is also used to define a constant value that cannot modify after it is defined.
var g= const[];
OPERATORS IN DART
An operator is a symbol that manipulates values or performs actions on their operand. The supplied equation is
5+5, where 5 and 5 are operands, and “+” is the operator.
Dart has many built-in operators for performing many sorts of tasks. Operators can be unary or binary, which
means that unary operators take only one operand and binary operators take two operands. There are several kinds
of operators.
Operator Types
Dart supports the following operator types:
Assignment operators
Arithmetic operators
Relational operators
Logical operators
Bitwise operator
Type test operators
Conditional operators
Casecade notation(..) operators
Types of operators.
Example:
void main(){
print("Example of Assignment operators");
var x1 = 15;
var x2 = 5;
print("x1+x2 = ${x1+x2}");
print("x1-x2 = ${x1-x2}");
print("x1*x2 = ${x1*x2}");
print("x1/=x2 = ${x1/x2}");
print("x1%x2 = ${x1%x2}");
}
Example:
void main() {
var a = 20;
print(a++); //postfix value
var b = 20;
print(++b); //prefix value,
var c = 30;
print(--c); //prefix value
var d = 15;
print(d--); } //postfix value
Assignment Operator
Assignment operators are used to giving variables values. It can also use in conjunction with the arithmetic
operators. The following is a list of assignment operators. Assume a has value of 30 and b has a value of 20.
Operators Name Description
= (Assignment Operator) It assigns the right operand to the right expression.
+=(Add and Assign) It adds the value of the right operand to the left operand and assigns the result back to the left operand. For example x+=y
→ x = x+y → 20
−=(Subtract and Assign) It subtracts the right operand’s value from the left operand’s value and assigns the result to the left operand. For example
x−=y → x = x−y → 30
*=(Multiply and Assign) It multiplies the operands and returns the result to the left operand. For example x*=y → x = x*y → 100
/=(Divide and Assign) It divides the left operand’s value by the right operand’s value and assigns the result to the left operand. For example x%=y
→ x = x%y → 3.0
∼/=(Divide and Assign) It divides the left operand’s value by the right operand’s value and returns the integer remaining quotient to the left operand.
For example x%=y → x = x%y → 2
Operators Name Description
%=(Mod and Assign) It divides the value of the left operand by the value of the right operand and returns the remainder to the left operand. For
example x%=y → x = x%y → 0
<<=(Left shift AND assign) The expression x<<=3 is equal to x = x<<3
>>=(Right shift AND The expression x>>=3 is equal to x = x>>3
assign)
&=(Bitwise AND assign) The expression x&=3 is equal to x = x&3
^=(Bitwise exclusive OR The expression x^=3 is equal to x = x^3
and assign)
|=(Bitwise inclusive OR and The expression x|=3 is equal to x = x|3
assign)
Example:
void main(){
print("Assignment operators");
var x1 = 12;
var x2 = 7;
x1+=x2;
print("x1+=x2 = ${x1}");
x1-=x2;
print("x1-=x2 = ${x1}");
x1*=x2;
print("x1*=x2 = ${x1}");
x1∼/=x2;
print("x1∼/=x2 = ${x1}");
x1%=x2;
print("x1%=x2 = ${x1}");
}
Relational Operator
Relational operators, often known as comparison operators, compare two expressions or operands. When two
expressions are compared, the result is a Boolean true or false. Consider the following table if x has 30 and y has
10.
Sr. Operator Description
1. >(greater than) x>y will return TRUE.
2. <(less than) x<y will return FALSE.
3. >=(greater than or equal to) x>=y will return TRUE.
4. <=(less than or equal to) x<=y will return FALSE.
5. ==(is equal to) x==y will return FALSE.
6. !=(not equal to) x!=y will return TRUE.
Example:
void main() {
var x = 20;
var y = 40;
print("Relational Operator");
var res = x>y;
print("x is greater than y: "+res. toString()); // We will learn the toString in next tutorial
var res0 = x<y;
print("x is less than y: "+res0. toString());
var res1 = x>=y;
print("x is greater than or equal to y: "+res1. toString());
var res2 = x<=y;
print("x is less than and equal to y: "+res2. toString());
var res3 = x!= y;
print("x is not equal to y: "+res3. toString());
var res4 = x==y;
print("x is equal to y: "+res4. toString());
}
Example:
void main()
{
var nums = 20;
var names = "Dart";
print(nums is int);
print(names is! String );
}
Logical Operators
Logical Operators are used to analyzing expressions and make decisions. Dart supports the logical operators are
listed in the following table.
Sr. Operator Description
1. &&(Logical AND) It returns if all the expressions are true.
2. ||(Logical OR) It returns TRUE if any of the expression is true.
3. !(Logical NOT) It returns a complement of expression.
Example:
void main(){
bool bool_vals1 = true, bool_vals2 = false;
print("logical operators");
var vals1 = bool_vals1 && bool_vals2;
print(vals1);
var vals2 = bool_vals1 || bool_vals2;
print(vals2);
var vals3 = !(bool_vals1 || bool_vals2);
print(vals3);
}
Bitwise Operators
The Bitwise operators perform on the value of the two operands bit by bit. The table of bitwise operators is shown
below.
Sr. Operators Description
1. &(Binary AND) It returns 1 if both the bits are 1.
2. |(Binary OR) It returns 1 if any of the bit is 1.
3. ^(Binary XOR) It returns 1 if both the bits are different.
4. ∼(Ones Compliment) It returns reverse of the bit. If bit is 0 then the compliment will be 1.
5. <<(Shift left) The value of the left operand moves left by the number of bits present in the right operand.
6. >>(Shift right) The value of the right operand moves left by the number of bits present in the left operand.
Example:
If x = 7
y = 6
Example:
void main(){
print("Example of Bitwise operators");
var x = 35;
var y = 30;
var z = 5;
// Bitwise AND Operator
print("x & y = ${x&y}");
// Bitwise OR Operator
print("x | y = ${x|y}");
// Bitwise XOR
print("x ^ y = ${x^y}");
// Complement Operator
print("∼x = ${(∼x)}");
// Binary left shift Operator
z = x <<2;
print("z<<1= ${z}");
// Binary right shift Operator
z = x >>2;
print("z>>1= ${z}");
}
First syntax:
condition? exp1 : exp2
If the specified condition is TRUE, it returns exp1, else it returns exp2.
Second Syntax:
exp1? ? expr2
If exp1 is not null, it returns its value; otherwise, it returns the value of exp2.
Example:
void main() {
var a = null;
var b = 30;
var val = a?? b;
print(val);
}
DOI: 10.1201/9781003299363-2
IN THIS CHAPTER
Constant and Number
String and Lists
Sets and Map and Symbol
Symbol and Enumeration
If, If-Else Statement
Loops
Boolean
We discussed Introduction to Flutter, Dart, covering history, features, advantages, and installation in the previous
Chapter. We also discussed the Basic syntax of Dart, data types, keywords, and operators.
DART CONSTANTS
A Dart Constant is an immutable object, which means it cannot be updated or modified while the application is
running. It cannot be reassigned once we assign a value to a constant variable.
Syntax:
final const_names;
or
final data_type const_names
Example:
void main () {
final x = 20;
final y = 30;
print(x);
print(y);
}
Syntax:
const const_names
Or
const data_type const_names
Example:
void main() {
const names= "Pihu";
print(names);
}
NUMBER IN DART
The Number data type is used to store the numeric value. It can be of two sorts in Dart:
Integer
Double
Numbers in Dart.
Dart Integer
Integer numbers are whole integers that may express without using a fractional component. For example, –20, 30,
–3215, 0, and so on. An integer can be either signed or unsigned. The integer value is represented as a non-decimal
number ranging from –263 to 263. In Dart, the int keyword is used to declare integer values.
int id = 401;
Dart Double
You may write a double number with a floating-point number or with a number with more decimal points. In Dart,
the double keyword is used to declare a Double value.
Example:
void main(){
int d = 5;
double pi = 3.147;
double rest = 4*pi*r*r;
print("The area of sphere = ${(rest)}");
}
void main(){
var x = num.parse("23.56");
var y = num.parse("25.63");
var z = x+y;
print("Sum is = ${z}");
}
Explanation: In this example, we used the parse() function to turn the numeric strings into integers, then placed
them in variables. We did an add operation and printed the output to the screen when the conversion was
accomplished.
Number Properties
Properties Description
Hashcode It returns the hash code of the number given.
isFinite It returns true if the provided number is finite.
isInfinite It returns true if the number is infinite.
isNan It returns true if the number is not negative.
isNegative It returns true if the number is negative.
Sign Depending on the sign of the provided number, it returns −1, 0, or 1.
isEven It returns true if the provided number is an even number.
isOdd It returns true if the provided number is odd.
Number Methods
Method Description
abs() It gives the absolute value of a given number.
ceil() It gives the ceiling value of a given number.
floor() It gives the floor value of a given number.
compareTo() It compares the value with other numbers.
remainder() It gives the truncated remainder after dividing the two numbers.
round() It returns a round of the number.
toDouble() It gives a double equivalent representation of the number.
toInt() Returns integer equivalent representation of the number.
toString() Returns String equivalent representation of the number.
truncate() Returns integer after discarding fraction digits.
STRING IN DART
Dart String is a character or UTF-16 code unit sequence. It is used to keep track of the text value. We can use
single or double quotes to create the string. The triple-quotes can be used to create a multiline string. Strings are
immutable, which means they are not changeable after they are created.
One can use the String keyword in Dart to declare a string. The string declaration syntax is shown below.
Syntax:
String msg = 'Welcome to Dart';
or
String msg1 = "This is double-quoted.";
or
String msg2 = ' ' ' line1
line2
line3'''
Printing String
To display the string on the screen, use the print() method. The string can be structured as a message, expression,
or object. Dart supports the $expression function, which wraps the value in a string. Consider the following
illustration:
void main() {
String strg1 = ' an example of a single-line string';
String strg2 = " an example of a double-quotes multiline line string";
String strg3 = """ a multiline line
string using the triple-quotes""";
var x = 20;
var y = 30;
print(strg1);
print(strg2);
print(strg3);
String Concatenation
To combine the two strings, use the + or += operator. The following is an example.
void main() {
String strg1 = 'Welcome ';
String strg2 = "to Dart";
String strg3 = strg1+strg2;
print(strg3);
}
String Interpolation
String interpolation is a method that allows you to alter a string and produce a new string by adding another value.
It can evaluate a string, including placeholders, variables, and interpolated expressions. String interpolation is
accomplished using the $expression. The expressions are replaced with the values that correspond to them.
Example:
void main() {
String strg1 = 'Hello ';
String strg2 = "Everyone";
String strg3 = strg1+strg2;
print(strg3);
var a = 29;
var b = 20;
Explanation: In the above code, we declared two strings variables, concatenated them, and displayed the result.
We established two variables with integer values, performed the mod operation, and displayed the result using
string interpolation.
As seen in the preceding example, we may utilize string interpolation as a placeholder.
String Properties
The string attributes provided by Dart are as follow.
Property Description
codeUnits It returns an unmodified list of UTF-16 code units of this string.
isEmpty If string is empty, it returns true.
Length It returns length of the string, including whitespace.
String Methods
The Dart offers a wide variety of approaches. The following is a list of a few key strategies.
LISTS IN DART
Dart Lists are similar to arrays in that they are an ordered collection of things. The array is the most popular and
widely used collection in any other programming language. The Dart list resembles JavaScript array literals. The
syntax for defining a list is shown below:
The Dart list is defined by enclosing all entries in square brackets ([]) and separating them with commas (,).
Let’s look at the list’s graphical representation:
list1: The list variable that corresponds to the list object is list1.
Index: Each element has an index number that indicates its position in the list. The index number, such as
list_name[index], is used to retrieve a specific entry from the list. The indexing begins at 0 and ends at length-
1, where length specifies the number of elements in the list. As an example: The preceding list is four items
long.
Elements: The actual value or dart object stored in the supplied list is referred to by the List elements.
Lists Types
The dart list is divided into two categories:
Fixed Length List
Growable List
The syntax shown above is used to create a fixed-size list. At runtime, we cannot add or remove elements. If we
try to change its size, it will raise an exception.
The following syntax is used to initialize the fixed-size list element.
Example:
void main() {
var list1 = new List(5);
list1[0] = 14;
list1[1] = 16;
list1[2] = 11;
list1[3] = 19;
list1[4] = 12;
print(list1);
}
Explanation: In the preceding example, we established a variable list1 that refers to a fixed-size list. The size of
the list is 5, and we added the elements matching their index position, where the 0th index contains 14, the 1st
index has 16, and so on.
Growable List
A Growable list is declared without specifying a size. One can change the Growable list’s size at runtime. The
syntax for declaring a Growable list is shown below.
Or
// creates list of the size zero
var list_names = new List()
In the following example, the empty list or list () constructor is used to create a list. The add() function is used to
add elements to a list dynamically.
Second example:
void main() {
var list1 = new List();
list1.add(14);
list1.add(12);
list1.add(18);
list1.add(11);
print(list1);
}
List Properties
The list’s properties are shown here.
Property Description
First It returns the case of the first element.
isEmpty If the list is empty, it returns true.
isNotEmpty If list has at least one element, it returns true.
Length It returns the list’s length.
Last It returns the list’s last element.
Reversed It returns us a list in reverse order.
Single It determines whether the list has just one element and returns it.
Syntax:
list_names.add(element);
Example:
void main() {
var odd_lists = [11,34,52,17,9];
print(odd_lists);
odd_lists.add(19);
print(odd_lists);
}
Explanation: In the above example, we have a list called odd_list that contains odd numbers. Using the add()
method, we added a new element 19 to the list. The add() method attached the element to the list’s end and
returned the changed list.
Syntax:
list_names.addAll([val1,val2,val3,?..valN]);
Example:
void main() {
var odd_lists = [21,32,15,72,19]
print(odd_lists);
odd_lists.addAll([13,11,14]);
print(odd_lists);
}
Explanation: In the above example, we do not need to use the add() method numerous times. The addAll()
function added many values simultaneously and returned the changed list object.
Syntax:
list_names.insert(index,value);
Example:
void main(){
List lsts = [13,43,22,45];
print(lsts);
lst.insert(21,19);
print(lsts);
}
Explanation: In the preceding example, we have a list of randomly generated integers. We used the insert()
method with the index 2nd value 19 as a parameter. It inserted the value at the second index before returning the
changed list object.
Syntax:
list_names.insertAll(index, iterable_list_of_value)
Example:
void main(){
List lsts = [31,43,12,25];
print(lsts);
lst.insertAll(0,[61,72,10,19]);
print(lsts);
}
Explanation: In the preceding example, we used the insertAll() method to append the list of items at the 0th index
position. It returned the list object after edit.
Updating List
Dart allows us to update the list, and we may edit it by simply accessing its element and assigning it a new value.
The syntax is shown below.
Syntax:
list_names[index] = new_value;
Example:
void main(){
var lists1 = [11,25,25,21,39];
print("List before updation: ${lists1}");
lists1[3] = 53;
print("List after updation:${lists1}");
}
Explanation: In the above example, we visited the third index, assigned the new value 53, and printed the result.
The preceding list has been updated to include the new value 53.
replaceRange()
The replaceRange() method in Dart is used to update list items within a defined range. It updates the element
values using the specified range. The syntax is shown below.
Syntax:
list_names.replaceRange(int start_val, int end_val, iterable);
Example:
void main(){
var lists1 = [19,11,29,22,32];
print("List before updation: ${lists1}");
lists1.replaceRange(0,4,[4,3,2,1]) ;
print("List after updation using replaceAll() function : ${lists1}");
}
Explanation: In the above example, we used the replaceRange() method on the list, which accepts three
parameters. As a third option, we gave the starting index 0th, the ending index 4th, and the list of components
changed. It returned a new list containing the substituted element from the specified range.
Syntax:
list_names.remove(value)
Explanation: In the preceding example, we called the list’s remove() method and gave the value 22 as an
argument. It eliminated the number 20 from the provided list and returned the updated list.
Syntax:
list_name.removeAt(int index)
Example:
void main(){
var lists1 = [14,11,12,19,13];
print("List before remove element : ${lists1}");
lists1.removeAt(3) ;
print("List after removing element : ${lists1}");
}
Explanation: In the above example, we gave the third index position as an input to the removeAt() method, which
deleted the 19 from the list.
Syntax:
list_names.removeLast()
Example:
void main(){
var lists1 = [11,31,69,72,81];
print("List before removing element:${lists1}");
lists1.removeLast();
print("List after removed element:${lists1}");
We invoked the removeLast() function in the above example, which deleted and returned the last element 81 from
the given list.
Syntax:
list_names. removeRange();
Example:
void main(){
var lists1 = [21,43,56,67,81];
print("List before removing element:${lists1}");
lists1.removeRange(1,3);
print("List after removed element:${lists1}");
}
Explanation: In the above example, we used the removeRange() function and gave as parameters start index
position 1 and end index position 3. It eliminated any elements that belonged between the given positions.
Example:
void main(){
var lists1 = ["Smiti","Petir","Handsi","Devanshi","Cruv"];
print("Iterating the List Element");
lists1.forEach((items){
print("${list1.indexOf(items)}: $items");
});
}
SETS IN DART
The Dart Set is an unordered collection of values of the same type. It offers a lot of the same functionality as an
array, except it’s not ordered. Set does not support storing duplicate values. The values in the set must be unique.
It is necessary to keep separate data of the same type in a single variable. We can only have one value of the
same type after we specify the set type. The set cannot maintain the order of the items.
Initializing Set
Dart has two ways for declaring/initializing an empty set. The set can be stated using curly braces ({}) followed by
a type argument, or the variable type Set can be specified using curly braces ({}). The syntax for declaring a set is
as follows.
Syntax:
var setNames = <type>{};
Or
Set<type> setnames = {};
The setnames specify the name of the set variable, and the type specifies the data type of the set.
Remember to note that the syntax of the set is quite similar to that of map literals. If we fail to declare the type
annotation with or without the variable to which it is allocated, the Dart compiler will generate a Map object
instead of a Set object.
Example:
void main(){
print("Initializing Set");
var names = <String>{"Smiti","Petir","Handsi","Devanshi"};
print(names);
}
Syntax:
Set_names.add(<value>);
Or
Set_names.addAll(val1,val2....valN)
Example:
void main(){
print("Insert element into Set");
var names = {"Jatin","Ruhi","Revanshi","Adami"};
// Declaring the empty set
var empy = <String>{};
empy.add("Jonathan");
print(empy);
// Adding the multiple elements
empy.addAll(names);
print(empy);
}
Explanation: Two sets of names and empty have been declared. The set names have few elements, whereas empy
is an empy set. Then, after adding the single element “Jonathan” using the add() function, we invoked the addAll()
method and gave another set of names as a parameter. Add the multiple values to the empy set.
Syntax:
Set_name.elementAt(index)
Example:
void main(){
print("Access element from the Set");
var name = {"Jatin","Ruhi","Devanshi","Arman"};
print(name);
var a = name.elementAt(3);
print(a);
}
Explanation: In the preceding example, we have assigned names. One can use the elementAt() function, and
index position 3 was supplied as an input. We made a variable x to retain the assessed value, and then we printed
the result.
Syntax:
set_name.contains(value);
Example:
void main() {
if(names.contains("Rishi")){
print("The Element is Found");
}
else {
print("The Element not found");
}
}
Explanation: In the preceding program, we used the contains() function and gave the value “Rishi” as an input to
discover the element in the given set. We utilized the conditional statement to determine whether or not an element
belonged to the provided set. When the given element in the set was present, the condition became true, and if one
wrote a block statement.
Note: In the following part, we will learn about conditional statements.
Syntax:
set_names.contains(values)
Example:
void main() {
names.remove("Peteri");
print("After remove : ${name}");
}
Explanation: We used the remove() function to delete “Peteri” from the specified set in the preceding program. It
returned the set object after it had changed it.
void main() {
print("Example of Remove Element in the given Set");
var name = <String>{"Peteri","Johny","Rishi","Devanshi","Finnie"};
names.forEach((values) {
print('Values: $values');
});
}
Syntax:
set_names.clear();
Example:
void main() {
print("Example of Remove All Element to the given Set");
var name = <String>{"Peteri","Johny","Rishi","Devanshi","Finnie"};
name.clear();
print(name);
Syntax:
List<type> <list_names> = <set_names>. toList();
void main() {
var a = <int>{10,11,12,13,14,15};
var b = <int>{12,18,29,43};
var c = <int>{2,5,10,11,32};
print("Example of Set Operations");
MAP IN DART
Dart Map is a kind of object that holds data as a key-value pair. Each value is connected with a key, which is used
to access its corresponding value. Keys and values can be of any kind. Each key in Dart Map must be unique,
although the same value can appear several times. The Map model is quite similar to the Python Dictionary
representation. Curly brackets ({}) are used to declare the Map, and commas (,) separate each key-value pair. Use
a square bracket ([]) to obtain the key’s value.
Syntax:
var map_names = {key1:value1, key2:value2 [.......,key_n: value_n]}
First example:
void main() {
var students = {'name':'Jay','age':'24'};
print(students);
}
Second example:
void main() {
var students = {'name':' Roy', 'age':24};
student['courses'] = 'M.tech';
print(students);
}
Explanation: In the preceding example, we declared a Map on a student’s name. Using a square bracket, we added
the value at runtime and passed the new key as a course associated with its value.
Syntax:
var map_names = new map()
map_names[key] = value
void main() {
var students = new Map();
student['names'] = 'Ria';
student['ages'] = 24;
student['courses'] = 'M.tech';
student['Branchs'] = 'Computer-Science';
print(students);
}
Map Properties
The Map class in the Dart:core:package defines the following properties.
Properties Explanation
Keys It is used to get all the keys as an iterable object.
Values It is used to get all the values as an iterable object.
Length It returns the length of the Map object.
isEmpty If the Map object contains no value, it returns true.
isNotEmpty If the Map object contains at least one value, it returns true.
Example:
void main() {
var students = new Map();
student['name'] = 'Roy';
student['age'] = 24;
student['course'] = 'M.tech';
student['Branch'] = 'Computer-Science';
print(student);
//isEmpty function
print(students.isEmpty);
//isNotEmpty function
print(students.isNotEmpty);
}
Map Methods
The most systematic approaches are listed below.
addAll(): It is a function that adds several key-value pairs of others. The syntax is shown below.
Syntax:
Parameter:
void main() {
Map students = {'name':'Roy','age': 24};
print('Map :${students}');
students.addAll({'dept':'Civil','email':'[email protected]'});
print('Map after adding the key-values :${students}');
}
remove (): It removes all pairings from the Map. The syntax is shown below.
Syntax:
Map.clear()
Example:
void main() {
Map students = {'name':'Roy','age': 24};
print('Map :${students}');
students.clear();
print('Map after removing all the key-values :${students}');
Remove (): If the key and its associated value exist in the provided Map, remove() removes them. The syntax
is shown below.
Syntax:
Map.remove(Object-key)
Parameter:
Keys: It removes the specified entries. It returns the value that corresponds to the specified key.
Example:
void main() {
Map students = {'name':'Roy','age': 24};
print('Map :${students}');
students.remove('age');
print('Map after removing the given key :${students}');
}
forEach(): It is used to loop through the Map’s entries. The syntax is shown below.
Syntax:
SYMBOL IN DART
A symbol object is used to specify a Dart programming language operator or identifier. Symbols are not required
for Dart programming in general, although they are helpful for APIs. It generally refers to identifiers by name
because identifier names can differ, but identifier symbols cannot.
Dart symbols are dynamic string names used to obtain metadata from a library. It primarily collects the
relationship between human-readable strings that have been improved for usage by computers.
Reflection is a technique used to metadata at runtimes, like several methods used in a class, the number of
constructors in a class, or the number of arguments in a function.
All reflection-related classes may be found in the Dart:mirrors library. Use it with both command-line and web-
based apps.
Syntax:
In Dart, the hash(#) symbol is followed by the name to define the Symbol. The syntax is shown below.
Syntax:
Symbol objt = new Symbol("names")
In this case, one might use a valid identifier such as a function, valid class, public member name, or library name
instead of the name value.
#bar
#radix
Example:
library foo_lib;
//the library name can be a symbol
class Foo {
// the class name can be a symbol
mt1() {
// the method name can be a symbol
print("Inside mt1");
}
mt2() {
print("Inside mt2");
}
mt3() {
print("Inside mt3");
}
}
We declared a class Foo in the library foo in the preceding code. The methods mt1, mt2, and mt3 are included in
the class. The above file is saved as foo. Dart.
Now we’ll make a new file called FooSymbol. Dart and run the code below.
FoolSystem.dart
import 'dart:core';
import 'dart:mirrors';
import 'Foo.dart';
main() {
Symbol libr = new Symbol("foo_lib");
//the library name stored as Symbol
if(checkIf_classAvailableInlibrary(libr, clsToSearchs))
//the searches Foo class in foo_lib library
print("class-found");
}
if (libMirror != null) {
print("Found-Library");
print("checkng....class details..");
print("The No of classes found is : ${libMirrors.declarations.length}");
libMirrors.declarations.forEach((s, d) => print(s));
main() {
Symbol libs = new Symbol("foo_lib");
Symbol clsToSearch = new Symbol("Foo");
reflect_InstanceMethods(libs, clsToSearch);
}
void reflect_InstanceMethods(Symbol libraryName, Symbol className) {
MirrorSystem mirrorSystems = currentMirrorSystem();
LibraryMirror libMirrors = mirrorSystems.findLibrary(libraryName);
if (libMirrors != null) {
print("Found-Library");
print("checkng….class details..");
print("No of classes found is : ${libMirrors.declarations.length}");
libMirrors.declarations.forEach((s, d) => print(s));
import 'dart:mirrors';
void main(){
Symbol libs = new Symbol("foo_lib");
String name_of_libs = MirrorSystem.getName(libs);
print(libs);
print(name_of_libs);
}
RUNES IN DART
Dart String, as previously said, is a series of characters, letters, digits, and unique characters. Dart Runes are a
series of UTF-16 Unicode characters, whereas the UTF-32 Unicode code points. The special symbol is printed
using a UTF-32 string. For example, the theta (Θ) symbol is represented by the Unicode equivalent\u0398; ‘\u’
refers to Unicode, and the values are hexadecimal. If the hex digits exceed four digits, they should be enclosed in
curly brackets ({}). Let’s look at an example to help us understand:
void main() {
var heart_runes = '\u2665';
var theta_runes = '\u{1f600}';
print(heart_runes);
print(theta_runes);
}
Dart offers the Dart: core library, which includes the Dart Runes. The String code unit can be accessed using one
of the three ways listed below.
Using String.codeUnitAt() Method
Using String.codeUnits property
Using String.runes property
String.codeUnitAt() Method
Using the codeUnitAt() function, we can go to the character’s code unit in the provided string. It takes the index
position as a parameter and returns the 16-bit UTF-16 code unit at the string’s given index point. The syntax is as
follows.
Syntax:
void main() {
String strg = 'DartTpoint';
print("Welcome to DartTpoint");
print(strg.codeUnitAt(0));
}
Explanation: The variable str in the above code stores the string value “DartTpoint.” We used the codeuUnitAt()
method and gave the index position as a parameter. It returned the 0th index character’s code unit.
String.codeUnits Property
The codeUnits property delivers a list of UTF-16 code units for a specified text. The syntax is shown below.
Syntax:
String.codeUnits;
void main() {
String str = 'DartTpoint';
print("Welcome to DartTpoint");
print(str.codeUnits);
}
Explanation: The codeUnits function produced a list of the code units corresponding to the provided character.
String.runes Property
The runes property is used to iterate through the UTF-16 code unit with the provided string. The syntax is shown
below.
Syntax:
String.runes
void main(){
"DartTpoint".runes.forEach((int rune) {
var characters=new String.fromCharCode(rune);
print(characters);
});
}
ENUMERATION IN DART
An enumeration is a collection of values known as elements, members, etc. This is critical since we performed the
procedure with limited variable values. For example, consider the days of the month, which can only be one of the
seven: Mon, Tue, Wed, Thur, Fri, Sat, and Sun.
Enumeration Initialization
The enumeration is defined using the enum keyword and a comma-separated list of valid identifiers. Curly braces
enclose this list. The syntax is shown below.
Syntax:
enum <enum_name> {
const1,
const2,
....., constN
}
The enum name represents the enum type name and the list of identifiers included within the curly bracket.
Each identifier in the enumeration list is assigned an index point. The first enumeration has an index of 0; the
second has an index of 1, and so on.
Example:
enum EnumofYear {
Jan,
Feb,
March,
April,
May,
June,
July,
Aug,
Sept,
Oct,
Nov,
Dec,
}
First example:
enum EnumofYears {
Jan,
Feb,
March,
April,
May,
June,
July,
Aug,
Sept,
Oct,
Nov,
Dec,
}
void main() {
print("DartTpoint - Dart Enumeration" );
print(EnumofYears.values);
EnumofWeek.values.forEach((vi) => print('value: $vi, index: ${vi.index}'));
}
Second example:
enum Process_Status {
none,
running,
stopped,
paused
}
void main() {
print(Process_Status.values);
Process_Status.values.forEach((vi) => print('value: $vi, index: ${vi.index}'));
print('running: ${Process_Status.running}, ${Process_Status.running.index}');
print('running index: ${Process_Status.values[1]}');
}
IF STATEMENTS
When the supplied condition returns true, the If statement lets us run a code block. We have a case in Dart
programming where we want to run a block of code when it meets the specified criteria. The condition analyses
the Boolean values TRUE or FALSE and decides based on these Boolean values.
Flowchart:
Statement of if.
Syntax:
If (condition) {
//statement(s)
}
The supplied condition is if statement will evaluate TRUE or FALSE; if true, the statement inside the if the body is
performed; if false, the sentence outside the if block is run.
Let’s have a look at few examples.
First example:
void main () {
// define variable which hold numeric value
var a = 39;
Explanation: We declared an integer variable n in the preceding program. In the if statement, we defined the
condition. Is the supplied number less than 45 or more than 45? The if statement checked if the condition was true,
then performed the if body and reported the result.
Second example:
void main () {
// define variable which holds a numeric value
var age = 19;
We can see in the preceding program that if evaluated, the condition to false, hence the execution bypassed the if
body and performed the outer statement of the if block.
IF-ELSE STATEMENT
When the specified condition is true, the if-block in Dart is performed. The else-block is run if the provided
condition is false. The else block is linked to the if-block.
Flowchart:
Statement of if-else.
The if-else statement is used here for either TRUE or FALSE results. If the supplied condition is true, then if the
body is executed; if the given condition is false, then the else body is executed.
First example:
void main() {
var a = 30;
var b = 40;
print("if-else statement");
};
}
Explanation: In the preceding code, we have two variables that hold integer values. When the given condition
assesses it as false, the else-block is printed.
Second example: Create a program to determine whether a given integer is even or odd.
void main() {
var num = 22;
print("if-else statement");
if(num%4 == 0){
print("Given number is even");
} else {
print("Given number is odd");
};
}
Explanation: In the preceding example, we had an integer variable num value of 22. We used the if-else statement
to determine if a given number is even or odd. The above condition assessed true since the modulus 22 is equal to
0, and the given number is printed on the screen as even.
IF ELSE-IF STATEMENT
The if else-if statement in Dart allows us to verify a series of test expressions and execute various statements. It is
utilized when we have to choose amongst more than two options.
Statement of if-else-if.
Syntax:
if (condition1) {
// statement
}
else if(condition2) {
// statement
}
else if (conditionN) {
// statement
}
.
.
else {
// statement
}
This construction style is also known as the else-if ladder in this area. From top to bottom, the condition is
assessed. When it finds the true condition, it executes the statement associated with that condition. When all
supplied conditions are false, the else block is performed.
Example:
void main() {
var marks = 64;
if(marks > 95)
{
print("Excellent");
}
else if(marks>70)
{
print("Very Good");
}
else if(marks>60)
{
print("Good");
}
else
{
print("Average");
}
}
Explanation: The above application outputs the outcome depending on the test scores. To print the result, we used
if else if. The integer value 64 has been assigned to the marks variable. We checked the program’s many
conditions.
Because the first condition is false, the marks will examine and check the second condition.
It compared to the second condition, found it to be true, and reported the result on the screen.
This operation repeats until all expressions are evaluated; control is transferred to the otherwise if ladder and
default statement is displayed.
We should experiment with the setting as mentioned earlier and see what happens.
Syntax:
if(condition1){
// code-1
if(condition2){
// code-2
}
}
Flowchart:
Statement of nested-if.
Long Description Unnumbered Figure 5
Example:
void main() {
var x = 30;
var y = 40;
var z = 50;
if (x>y){
if(x>z){
print("x is greater");
}
else{
print("z is greater");
}
}
else if (y>z){
print("y is greater");
}
else {
print("z is greater");
}
}
In the preceding program, we declared three variables of 30, 40, and 50: x, y, and z. In the outer if-else condition,
we specified that a must be more significant than b. The inner block will be performed; otherwise, the outer block
will be executed.
Another condition in the inner block tests is if a variable is more significant than variable c. If the condition is
true, the inner block will be performed.
Our software returned false in the first condition and then skipped the inner block check for the second
condition. If the condition is met, the output is printed.
Syntax:
switch( expression )
{
case value1:{
//statement
Block1;
}
break;
case value2:{
//statement
Block2;
}
break;
case valueN:{
//statement
BlockN;
}
break;
default: {
//statement;
}
}
Example: The expression can be either an integer expression or a character expression in this case. The case labels
are represented by the values 1, 2, n, and they are used to identify each case specifically. Each label must be
followed by a colon (:).
The labels must be distinct since the same name label will cause difficulty while running the application.
The case label is connected with a block. A block is just a collection of several assertions for a specific situation.
Once the switch expression has been evaluated, the expression value is compared to all cases declared within the
switch case. Assume the expression’s value is 2, and then compare it to each case until it finds the label 2 in the
program.
One must use the break statement after each case. Suppose we do not include the break statement. In that case,
the specified case is identified; the program continues to execute all of the cases until the program’s conclusion is
reached. To declare the break statement, utilize the break keyword.
When the value of the expression does not match any of the cases, the default case is run. It is not required to
write in the program.
First example:
void main() {
int a = 6;
switch (a) {
case 1:
print("Value is 2");
break;
case 2:
print("Value is 4");
break;
case 3:
print("Value is 6");
break;
case 4:
print("Value is 8");
break;
default:
print("Out of range");
break;
}
}
In the above program, we set the variable n to 6. We built the switch case using the phrase, which compares each
case with the variable n. Because the value is 6, case-label 3 will be executed. If case-label 3 is located
successfully, the result is printed on the screen.
Second example:
void main()
{
// declaring a interger variable
int Roll_nums = 90013;
// Evalaute the test-expression to find the match
switch (Roll_nums) {
case 90008:
print("My name is Tia");
break;
case 90011:
print("My name is Peten");
break;
case 09008:
print("My name is Devanshia");
break;
// the default block
default:
print("Roll number is not found");
}
}
Explanation: We assigned the number 90013 to the variable Roll num in the preceding program. The switch test
expression validated all instances indicated within the switch statement. When the test expression did not match
the cases, it produced the default case statement.
LOOPS IN DART
Dart Loop is used to run a block of code repeatedly for a defined number of times or until the stated condition is
met. Loops are fundamental components of any programming language. It is used to iterate across Dart iterables
like list, Map, and so on and execute actions many times. A loop may be divided into the loop body and control
statements. The Loop’s primary goal is to run the function several times. Dart supports the following loop types.
Dart for Loop
Dart for in Loop
Dart while Loop
Dart do-while Loop
Syntax:
for(Initialization; condition; incri/decri)
{
// loop body
}
The initialization function is used as a starting value in a loop and is only executed once.
A condition or test expression returns True or False results. The for loop will continue to execute until the
condition is met.
The Loop is terminated when the condition evaluates to false.
The incr/decr function is used to increase or reduce a variable.
Example:
void main()
{
int nums = 3;
for(nums; nums<=10; nums++)
{
print(nums); //to print the number
}
}
}
}
For in Loop
The for in Loop differs somewhat from the for Loop. It just uses a dart object or expression as an iterator and
iterates through the elements one at a time. The element’s value is tied to var, which is valid and accessible to the
loop body. The Loop will run until there are no more elements in the iterator. The syntax is shown below.
Syntax:
for (var in an expression)
{
//statement
}
Example:
void main()
{
var list = [12,23,31,43,55];
for(var c in list) //for..in loop to print list element
{
print(c); //to print number
}
}
While Loop
When the number of executions of a code is unknown, the while loop is employed. It will run as long as the
requirement is met. It first verifies the supplied condition and then executes the while loop’s lines. The while loop
is most commonly used to generate an endless loop. The syntax is shown below.
Syntax:
while(condition) {
//body of loop
}
Example:
void main()
{
var c = 2;
var maxnum = 10;
while(c<maxnum){ // it will
print until expression return false
print(c);
c = c+1;
// increase the value 1 after each iteration
}
}
void main()
{
int a = 1;
while (a <= 5)
{
print( a);
--a;
}
}
Example:
void main() {
int a1=1;
int a2=1;
// We are checking multiple condition by using logical operators.
while (a1 <= 4 && a2 <= 3)
{
print("a1 : ${a1}, a2: ${a2}");
a1++;
a2++;
}
}
Explanation: In the preceding code, we gave 1 to two variables, a1 and a2. In the while loop, we verified various
circumstances where n1 is less than or equal to 4 and n2 is less than or equal to 3.
It tested both values and reported the result on the first iteration. When the sum of a1 and a2 equals to 4, this
occurs at one place. Because a1 met condition one but a2 did not satisfy condition two, the Loop is halted, and the
result is printed on the screen.
Do-While Loop
The do-while Loop is identical to the while loop, except it runs the loop statement before checking the specified
condition. The syntax is shown below.
Syntax:
do {
// body
} while(condition);
Example:
void main()
{
var c = 2;
var maxnum = 10;
do
{
print("Value is: ${c}");
c = c+1;
}while(c<maxnum);
}
BOOLEAN IN DART
The Dart Boolean data type determines if a statement is true or false. True and false are the Boolean type’s two
values, both compile-time constants. In Dart, the numeric values 1 and 0 do not describe whether something is true
or false. The term bool is used to express a Boolean value. The syntax for defining the Boolean variable is as
follows.
Syntax:
bool var_names = true;
OR
bool var_names = false;
Example:
void main()
{
bool check;
check = 24>10;
print("statement is = ${check}");
}
Explanation: We declared the bool variable check, which will use to validate the given expression. We printed the
result of the expression 24>12 since it returned true.
CHAPTER SUMMARY
In this chapter, we discussed data types and control flow statements, where we also covered Constants, Strings,
Lists, Sets, Maps, Symbols, Runes, and Enumeration. Moreover, we also discussed if, if-else statements, switch
statements, and loops.
CHAPTER 3
Dart Functions and Object-Oriented
Programming
DOI: 10.1201/9781003299363-3
IN THIS CHAPTER
Anonymous and Main Function
Recursion
Constructor
Inheritance
Overriding
Interfaces
In the previous chapter, we discussed data types and control flow statements. In this chapter, we cover data
function and object-oriented where we also discuss the main function and recursion. Moreover, we discuss
constructor, inheritance, methods, overriding, and interfaces.
FUNCTION IN DART
A Dart function is a collection of programs that work together to complete a specified purpose. It is used to divide
big amounts of code into smaller modules that may be reused as needed. Functions make the software more
readable and debug. It improves the modular approach and code reusability.
Assume we develop basic calculator software in which we must conduct operations several times when the user
inputs data. For each calculator operator, we may write a distinct function. We don’t have to create code for
adding, subtracting, multiplying, and dividing over and again by using functions. We can call the functions several
times to use them multiple times.
The method allows you to run a code numerous times with varied values. A function can be called as a
parameter at any time and returns some value to the place where it was called.
Function Benefits
The Dart function has a few advantages, which are listed below.
It improves the modular method of problem-solving.
It improves the program’s reusability.
We can link the programs together.
It improves the code.
It facilitates debugging.
It simplifies development and reduces complexity.
Function Defining
A function can define by specifying the function name and the relevant parameter and return type. A function
comprises a collection of statements known as the function body. The syntax is shown below.
Syntax:
return_type func_name (parameter_list):
{
//statement
return value;
}
Calling a Function
After creating a function, we may call or invoke it within the main() function body. A function is called simply by
its name, with or without an argument list, if any. The syntax is shown below.
Syntax:
fun_name();
or
variable = function_name(argument);
Example:
mul(20,30);
Syntax:
int sum(int a, int b)
{
……
……
return result;
}
var x = sum(30,20)
Syntax:
return <expression/values>
Example:
return results;
Function Examples
Let’s discuss functions by creating a program that adds two integers using functions.
Explanation: We declared a function named sum() and passed two integer variables as actual parameters in the
preceding example. We defined a result variable in the function body to hold the sum of two integers and return the
result.
We invoked a function with the same name and passed formal arguments 40 and 10 to add two numbers. The
sum() function produced a result, which we saved in the variable c and reported on the console.
Syntax:
return_type func_name()
{
//Statement;
return value;
}
void main(){
// Creation of afunction without argument
String greeting(){
return "Welcome to DartTpoint";
}
// Calling the function inside print statement
print(greeting());
}
Explanation: In the preceding example, we constructed a method called greeting() that took no arguments and
returned a string value to the caller function. Then, within the print statement, we ran the greeting() function and
output the result to the console.
Syntax:
func_name()
{
//statement..
}
Or
void fun_name()
{
//statement..
}
Explanation: In the preceding example, we defined a function called greeting() outside of the main() method
before writing the print statement. We invoked the defined function within the main() function and reported the
output to the console.
void main()
{
void number(int a){
// Check given number is even or odd
if (a%2 ==0){
print("Given number is even");
}
else {
print("Given number is odd");
}
}
number(30);
}
Syntax:
(parameter_list) {
statement
}
Example:
void main() {
var lists = ["Jamin","Patric","Mathini","Tony"];
print("The Example of anonymous function");
list.forEach((items) {
print('${list.indexOf(items)}: $items');
});
}
Explanation: We defined an anonymous function with an untype parameter item in the preceding example. The
function was run for each item in the list and printed the strings with specified index value.
If the function has one statement, we may express the above code in the following manner.
list.forEach(
(items) => print("${list.indexOf(items)}: $items"));
Lexical Scope
Dart is a lexical scope language, which implies that the variable’s scope is determined at compile-time, as we
stated in the introduction. When code is compiled, the variable’s scope is determined. If the variable is defined in
different curly brackets, it operates differently. Let’s have a look at an example:
void main() {
var inside_Main = true;
// Defining a Nested Function
void myFunction() {
var inside_Function = true;
void nestedFunction() {
var inside_NestedFunction = true;
// This function is using all the variable of the previous functions.
assert(topVariable);
assert(inside_Main);
assert(inside_Function);
assert(inside_NestedFunction);
}
}
}
Lexical Closure
A closure, also known as a lexical closure, is a function object with access to variables in its lexical scope even
when the function is invoked outside its original scope. In other words, it allows access to the scope of an outside
function from an inside function. Let’s have a look at an example:
void main() {
String initial() {
var names = 'Will Smith'; // name is local variable created by init
Explanation: The initial() method in the above code established a local variable named name and a function called
disp_Name (). The disp_Name() function is defined within the initial() method; therefore, it has no local variables.
The inner function can access the variable of the outer functions. The method disp_Name() has access to the
name variable defined in the outer function, which is initial().
Syntax:
void main() {
// the main function body
}
Example:
void main()
{
print("Welcome To DartTpoint");
}
Syntax:
return <expression/value>;
Dart Value with Return Value
Syntax:
return_type function_name()
{
//statement;
return value;
}
void main() {
int mul(int x, int y){
int z = x*y;
return z;
}
print("The multiplication of two numbers: ${mul(20,40)}");
}
WHAT IS RECURSION?
Dart Recursion is a way in which a function calls itself a subroutine. It is used to tackle challenging problems by
breaking them down into smaller parts. When a function is called again or recursively, this is referred to as
recursion.
Iterators can solve issues, although recursion is suggested for programmers to employ when dealing with
complicated problems since it is an effective problem-solving strategy. The same complex job may evaluate in less
time and code.
Recursion creates several calls to the same function; nevertheless, there should be a base case that terminates the
recursion.
Recursion employs the divide and conquers strategy to accomplish a complicated mathematical computing
assignment. It breaks down extensive work into smaller bits.
It is not suggested to use recursion to solve all sorts of issues. It is, nevertheless, best for a few questions like
searching, sorting, Inorder/Preorder/Postorder, Tree Traversal, and DFS of Graph algorithms. However, it must do
it properly; otherwise, it will result in an eternal loop.
void main() {
int factorial(int nums){
Explanation: The factorial() method in the above example is a recursive function since it calls itself. When we
supply the integer value 5 to the factorial() function, it will recursively call itself by reducing the number.
The factorial() procedure will be run until it matches the base condition or equals one. It multiplied the number
by the number’s factorial. Consider the following recursive call explanation.
The recursion ends when the number is reduced to one, which is the fundamental condition of recursion.
To avoid endless calls, a recursion function must contain a base condition.
Recursion has the following disadvantages:
Recursive calls use a lot of memory, so they are inefficient.
Debugging recursive routines is challenging.
It might be challenging to understand the rationale behind the recursion at times.
Class
Dart classes are the blueprints for the linked objects. A Class is a user-defined data type that outlines its attributes
and behavior. To obtain all of the class’s properties, we must first construct an object. The class syntax is shown
below.
Syntax:
class Class-Name
{
<fields>
<getter/setter>
<constructor>
<functions>
}
Object
An object is a real-life entity such as a table, a person, a car, etc. The object has two properties: its state and its
behavior. Consider an automobile, which has a name, model name, price, and behavior such as moving, stopping,
and so on. Object-oriented programming allows you to identify an object’s state and behavior.
By creating an object of that class, we may access its attributes. The object in Dart may create by using the new
keyword followed by the class name. The syntax is shown below.
Syntax:
var object-tName = new
Class-Name(<constructor_arguments>)
Inheritance
Dart supports inheritance, which allows us to create new classes from existing ones. The class to be extended is
referred to as the parent/superclass, and the newly created class is referred to as the child/subclass. Dart offers the
extended keyword for inheriting parent class attributes in child classes. The syntax is shown below.
Syntax:
class child_class_name extends parent_class_name
Polymorphism
Polymorphism is a notion in object-oriented programming in which one entity has several forms. There are two
forms of polymorphism: runtime polymorphism and compile-time polymorphism. For instance, a function with the
same name but a distinct behavior or class. Another example is the shape() class and all the classes that inherit
from Rectangle, Triangle, and Circle.
Interfaces
The interface is specified as a class blueprint. We may define methods and variables within the interface the same
way we do in the class, but the interface only allows for abstract method creation. We can only declare the function
signature, not the function body. The interface can be implemented by another class. It is mostly used to hide data.
Abstract Class
An abstract class has one or more abstract methods. The abstract class may declare by using the abstract keyword
followed by the class definition. The syntax is shown below.
Syntax:
abstract class Class-Name {
//Body of the abstract class
}
Syntax:
class Class-Name
{
<fields>
<getters/setters>
<constructor>
<functions>
}
The Class-Name variable represents the actual name of the class, as defined by the user. A class definition is
provided in curly brackets. Fields, constructors, getters, setters, and methods can all be found in a class.
Example:
void main()
{
// Class Defining
class Students {
var stdNames;
var stdAges;
var stdRoll_num;
//the Class Function
showStdInfo() {
print("The Student Name is : ${stdNames}");
print("The Student Age is : ${stdAges}");
print("The Student Roll Number is : ${stdRoll_num}")
}
In the preceding class example, we declared a class called Student. This class contains three fields:
standardNames, standardAges, and standardRoll_num. showStdInfo() is a class function that prints the class’s
fields. To access the class’s properties, we must first construct its object.
Object in Dart
Dart is an object-oriented programming language in which everything is viewed as an object. An object is a
variable or instance of a class used to access the properties of the class. Objects have two characteristics: state and
behavior. Assume a guy has a state (name, age, and health) and a behavior (walking, running, and sleeping).
Programming objects are conceptually comparable to real-world objects in that they have state and behavior. A
class is a template from which an object is created.
Classes’ fields are maintained as object states, whereas methods reflect an object’s action.
Syntax:
var object-name = new
class-name(<constructor_arguments>);
In this case, object name and class name represent the actual object name and class name, respectively. If the
constructor of the class is parameterized, the constructor parameters must pass a value.
Example:
// Defining class
class Students {
var stdNames;
var stdAges;
var stdRoll_num;
// Class Function
showStdInfo() {
print("The Student Name is : ${stdNames}");
print("The Student Age is : ${stdAges}");
print("The Student Roll Number is : ${stdRoll_num}")
}
}
void main () {
// Creation of Object called std
var std = new Students();
}
We created the object std of the type Student, but simply creating an object is not enough. We must use the newly
formed object to access the properties.
Syntax:
objectName.prop-Name or objectName.metho-Name()
Example:
// Defining class
class Students {
var stdNames;
var stdAges;
var stdRoll_num;
// defining class function
showStdInfo() {
print("The Student Name is : ${stdNames}");
print("The Student Age is : ${stdAges}");
print("The Student Roll Number is : ${stdRoll_num}");
}
}
void main () {
// Creating object called std
var stdt = new Student();
stdt.stdNames = "Peterin";
stdt.stdAges =22;
stdt.stdRoll_num = 90011;
// Accessing class Function
std.showStdInfo();
}
Explanation: In the preceding example, we constructed a class named Student, which included the student’s
name, age, and roll number, as well as the showStdInfo() function, which displayed the student’s data.
Then, using the (.) operator, we created a Student class object and assigned values to each field. We used the
showStdInfo() method, which produced the details to the screen.
Example:
As shown below, assume we have a class name Student and want to create an object from it.
Student stdt = new Students()
Creating Constructor
As previously stated, a constructor has the same name as its class and does not return any value. If we have the
class Student, the constructor’s name should also be Student.
Syntax:
class Class-Name {
Class-Name() {
}
}
When creating a constructor, we must keep the following two rules in mind:
The constructor and class names should be the same.
There is no explicit return type for the constructor.
Example:
void main() {
// Creating object
Student stdt = new Students("Jonephs",29);
}
class Students{
// Declaring a construstor
Students(String strt, int ages){
print("The name is: ${strt}");
print("The age is: ${ages}");
}
}
Explanation: In the preceding example, we defined a function Object() constructor method called Student(),
which is also the name of the class. In the constructor, we supplied two parameters. When we created an object of
the Student class and passed a value, it immediately ran the function Object() constructor and reported the result.
Types of Constructors
Dart has three types of constructors, which are listed here.
Default Constructor or no-arg Constructor
Parameter Constructor
Named Constructor
Syntax:
class Class-Name {
Class-Name() {
// constructor body
}
}
Example:
void main() {
// Call constructor automatically when we creates an object
Student stdt = new Students();
}
class Students{
// Declaring construstor
Students(){
print("Example of default constructor");
}
}
Parameterized Constructor
We may also pass arguments to a constructor, known as a parameterized constructor. It is used to set up instance
variables. We may require a constructor that accepts a single or several arguments. The parameterized constructors
are mainly used to set the values of instance variables. The syntax is shown below.
Syntax:
class Class-Name {
Class-Name(parameter_list)
// constructor body
}
Example:
void main() {
// Creating an object
Student stdt = new Students("Jonesph",28);
}
class Students{
// Declaring a parameterized constructor
Student(String strt, int ages){
print("The name is: ${strt}");
print("The age is: ${ages}");
}
}
Explanation: We specified a parameterized constructor with two parameters named names and ages in the
preceding example. We created a Student class object and gave the proper value to the constructor. As an output to
the screen, it printed the names and ages.
Named Constructors
Multiple constructors in a single class are declared using named constructors. The syntax is shown below.
Syntax:
Class-Name.constructor_name(param_list)
Example:
void main() {
// Creating an object
Students stdt1 = new Students(); // object for Default constructor
Students stdt2 = new Students.namedConst("Computer-Science"); // object for parameterized
}
class Students{
// Declaring construstor
Students(){
print("Example of the named constructor");
}
// Second constructor
Students.namedConst(String branchs){
print("Branch is: ${branchs}");
}
}
// Creating a constructor
Mobiles(modelnames, man_years){
modelnames = modelnames;
man_years = 2021;
print("Mobile's model name: ${modelnames}, and the manufacture year is: ${man_years
}
}
void main(){
Mobiles mob = new Mobiles("iPhone 13 ",2021);
}
Explanation: In the preceding program, we defined a class named Mobile, which contains two attributes:
modelnames and man_years. Then we created a constructor and gave the same parameters as the names of the
class attributes.
The constructor arguments with the same name are used to assign the class variables (attributes) on the left side
of the constructor body. When we make an instance of a class, the constructor is automatically run, and the result is
reported.
If several arguments have the same name, the Dart compiler may become confused. As a result, the compiler
will generate ambiguity. That is why we use the term “this” to refer to the current class object.
Explanation: The preceding example is identical to the previous program, with the exception of this keyword.
this.man_years = 2021;
this.modelnames = modelnames
We utilized this keyword to distinguish an instance or class variable from a local variable.
Remember:
This keyword is used to point to the current class object.
It may use to refer to the variables in the current class.
Using this term, we may instantiate or call the current class constructor.
This keyword can be passed as an argument to the constructor call.
This keyword can pass as a parameter in the method call.
It resolves any ambiguity or name conflict in our instance’s or object’s constructor or function.
It may use to get the current instance of the class.
Local Variables
Local variables are defined in methods, constructors, or blocks. It is formed when we create a method or
constructor whose scope is limited to those objects. A local variable cannot use outside of the method, constructor,
or block.
Class Variable
A class-variable, also known as a static member variable, is a variable that is declared using the static keyword. It
is declared in the class but not within a constructor, function, or block. All instances share a single copy of the
class variable, or all instances of that class share class variables.
Instance Variable
The instance variable, often known as the non-static variable, is used to declare variables without using the static
keyword. An object specifies the instance variables. These variables may access by using the class instance.
Syntax:
static [datatype] [variablename];
Syntax:
ClassName.staticVariableName;
Static Method
The concept of the static method is similar to that of the static variable. Instead of a class instance, static methods
are class members. Static methods can only use static variables and call the class’s static methods. We do not need
to construct an instance of the class to access it. We may do so when we wish to use a static method in another
class.
Remember the following:
Instead of its object, the static methods are the member class.
Class methods are another name for static methods.
The class name can use to access static methods.
A particular copy of the static method is distributed across all class instances.
Syntax:
static return_type method_name() {
//statement
}
Syntax:
class-Name.staticMethod();
Example:
class Students {
static String stdBranchs; // Declaring static variable
String stdNames;
int roll_nums;
showStdInfo() {
print("The Student's name is: ${empNames}");
print("The Student's salary is: ${roll_nums}");
print("The Student's branch name is: ${stdBranchs}");
}
}
void main() {
Students std1 = new Students(); // Creating instances of the student class
Students std2 = new Students();
// Assigning value of the static variable using class name
Students.stdBranchs = "Computer-Science";
std1.stdNames = "Benin willian";
std1.roll_nums = 90013
std1.showStdInfo();
std2.stdNames = "Peterin Handsi";
std2.roll_nums = 90038
std2.showStdInfo();
}
Explanation: In the above code, we declared the Student class, which has three fields, including the static variable
stdBranchs, and one function showStdInfo (). We generated two instances of the class Students and set values to
the variables in the class.
The class name and associated value are used to access the static variable stdBranchs. The showStdInfo()
method was then invoked by objects std1 and stu2. As an output, it printed the student’s information.
SUPER KEYWORD
The super keyword signifies the current child class’s immediate parent class object. Its child class uses it to invoke
superclass methods and superclass constructors. The primary goal of the super keyword is to eliminate
misunderstandings between parents and subclasses with the same method name. It is also used to refer to the
properties and methods of the superclass.
Syntax:
Super.var-Name
Example:
// Super class Car
class Cars
{
int speeds = 190;
}
// sub class Bike extending Car
class Bikes extends Cars
{
int speeds = 130;
void display()
{
//print varible of the base class (Bikes)
print("Speed of car: ${super.speeds}");
}
}
void main() {
// Creating a object of sub class
Bikes b1 = new Bikes();
b1.display();
}
Explanation: In the above code, we declared the superclass as Cars, which contains speeds variable, and then the
subclass Bikes inherited it.
Because the speeds of the subclass are changeable, we utilized the super keyword to retrieve the parent class
variable. We generated a child class b1 object and ran a show method that reported the value of the superclass
variable.
When we use print(speeds) instead of print(super.speeds), the value of the subclass variable is printed.
We may copy the preceding code, put it into a dartpad or notepad, and print the value without using the super
keyword. We can tell the difference between the two outcomes.
Syntax:
super.method-Name;
Example:
// Base class Supers
class Supers
{
void display()
{
print("This is super class method");
}
}
// Childs class inherits Supers
class Childs extends Supers
{
void display()
{
print("This is child class");
}
// Note that message() is only in the Student class
void messages()
{
// will invoke or call the current class display() method
display();
// will invoke or call the parent class display() method
super.display();
}
}
void main() {
// Creating the object of sub class
Childs c1 = new Childs();
// calling display() of Students
c1.message();
}
Explanation: In the preceding code, we built a function with the same name in parent and child classes. The
show() function is present in both the parent and child classes, showing that method overriding has occurred.
So we built a messages() method in the child class, called the parent class function within it using the super
keyword, and then generated the child class object. We used the object to invoke the messages() function, which
displayed both show() method statements on the screen.
Syntax:
:super();
Example:
// Base class called Parents
class Parents
{
Parents()
{
print("This is super class constructor");
}
}
Explanation: The syntax of the Dart language is too similar to that of the C# language. We used the super
keyword to invoke the parent class constructor, separated by colon (:). We should use the superclass as an
initializer when delegating a superclass constructor.
INHERITANCE IN DART
Dart inheritance is described as the process of deriving another class’s features and characteristics. It allows us to
construct a new class from an existing one. It is the most important notion in the oops. All of the prior class’s
behavior and characteristics can reuse in the new class.
Parent class: A class inherited by another class is referred to as a superclass or parent class. It is sometimes
referred to as a basic class.
Child class: A child class inherits properties from another class. It is sometimes referred to as a derived class
or a subclass.
Assume we have a fleet of cars and divided them into three classes: Duster, Maruti, and Jaguar. The modelName(),
milage(), and man year() methods will be the same for all three types.
Inheritance of class.
Syntax:
class childclass extends parentclass {
//body of the child class
}
Using the extends keyword, the child class inherits functions, variables, or properties from the parent class. It
cannot inherit the parent class’s constructor; we shall go over this later.
Inheritance Types
There are four forms of inheritance. These are provided here.
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Single Level Inheritance
A single class or subclass inherits a class is inherited by one parent class in single inheritance. In the following
example, we construct a Person class inherited from the Human class.
Single inheritance.
class Birds{
void fly()
{
print("Bird can fly");
}
}
// Inherits super class
class Parrots extends Birds{
//child class function
void speak(){
print("Parrot can speak");
}
}
void main() {
// Creating object of child class
Parrots p1=new Parrots();
p1.speak();
p1.fly();
}
Explanation: In the above code, we declare the fly() function in the parent class Birds. Then, using the extends
keyword, we constructed the Parrots child class, which inherited the parent class’s properties. The function speak
is unique to the child class ().
The kid class now has two functions: fly() and speak(). As a result, we generated a child class object and used it
to access both functions. It output the outcome to the console.
Multilevel Inheritance
A subclass is inherited by another subclass or creates a chain of inheritance in multiple inheritance. Let’s have a
look at an example:
Multiple inheritance.
class Birds{
void fly()
{
print("Bird can fly");
}
}
// Inherits super class
class Parrots extends Birds{
void speak(){
print("Parrot can speak");
}
}
// Inherits Parrots base class
class Eagles extends Parrots {
void vision(){
print("Eagle has a sharp vision");
}
}
void main() {
// Creating object of the child class
Eagles e1=new Eagles();
e1.speak();
e1.fly();
e1.vision();
}
Explanation: In the preceding example, we built a new class called Eagles and inherited it from the Parrots class.
The parrot is now the parent class of Eagles, and Eagles has inherited all of the functions of both parent classes.
We generated a child class object and accessed all of its attributes. It displayed the output on the screen.
Hierarchical Inheritance
Two or more classes inherit a single class in hierarchical inherence. The Persons class is inherited by the two-child
classes Peterin and Jamesph in the following example:
Hierarichal inheritance.
// Parent Class
class Persons {
void dispName(String names) {
print(names);
}
void dispAge(int ages) {
print(ages);
}
}
class Peterin extends Persons {
void dispBranch(String nationality) {
print(nationality);
}
}
//Derived class created from another derived class.
class Jamesph extends Persons {
void result(String results){
print(results);
}
}
void main() {
// Creating Object of James class
Jamesph j1 = new James();
j1.dispName("Jamesph");
j1.dispAge(25);
j1.results("Passed");
// Creating Object of Peter class
Peter p1 = new Peterin();
p1.dispName("Peterin");
p1.dispAge(21);
p1.dispBranch("Computer-Science");
}
Syntax:
Sub_ClassConstructor():super() {
}
Implicit Super
When we instantiate a class, the constructor is immediately invoked, as we all know. When we create an object of
a subclass, the subclass’s constructor is invoked, which automatically executes the parent class’s default (non-
parameterized) constructor. To invoke the superclass constructor, we may utilize the super() constructor in our
subclass. Let’s have a look at an example:
// Parent class
class Super_class {
Super_class(){
print("Superclass constructor");
}
}
class Sub_class extends Super_class
{
Sub_class(){
print("Subclass constructor");
}
display(){
print("Welcome to DartTpoint");
}
}
void main(){
print("Dart Implicit the Superclass constructor call");
// We create an object of sub class which will invoke the subclass constructor.
// as well as the parent class constructor.
Sub_class s1 = new Sub_class();
// Calling sub class method
s1.display();
}
Explicit Super
If the superclass constructor has parameters, we must explicitly execute the superclass constructor in the subclass
by calling super() constructor with argument in. Let’s have a look at an example:
// Parent class
class Super_class {
Super_class(String msgs){
print("Superclass constructor");
print(msgs);
}
}
class Sub_class extends Super_class
{
Sub_class():super("We are calling the superclass constructor explicitly "){
print("This is a subclass constructor");
}
display(){
print("Welcome to javatpoint");
}
}
void main(){
print("Dart Implicit the Superclass constructor example");
// We create an object of the sub class which will invoke subclass constructor.
// as well as the parent class constructor.
Sub_class s1 = new Sub_class();
// Calling the sub class method
s1.display();
}
METHODS IN DART
A Dart method is a set of statements that include certain class object properties. It allows us to conduct various
operations, and we can call it by name when we need to in the program. Methods break a huge job into little bits
and carry out the program’s specific operation. This strategy boosts code reusability and improves the program’s
modular approach. The methods can be constructed using arguments supplied as information to perform the
specified task, after which it can return a value or return nothing. Methods in a class that define either instance
methods or class methods.
Instance Methods
A method that may be accessed by utilizing a class instance is referred to as an instance method. The instance
methods can have no or many parameters. This keyword may access via the instance method through the instance
variable.
Syntax:
return_type method_name(<list of argument(s)>)
{
//statement
}
Syntax:
Class_Name objName = new ClassName()
obj_Name.methodName()
Class Methods
The static keyword is used to declare the class method. It is accessible by utilizing the class name rather than the
class object. These methods are shared by all instances of that specific class. The Static methods can only access
static variables.
Syntax:
Class_Name.classMethod()
void main() {
// Creating objects
//of both the classes
SuperClass s1 = new SuperClass ();
SubClass s2 = new SubClass ();
First example:
class Humans{
//Overridden-method
void run()
{
print("The Human is running");
}
}
class Men extends Humans{
//Overriding-method
void run(){
print("The Boy is running");
}
}
void main(){
Men m1 = new Men();
//This will call child class version of run()
m1.run();
}
Explanation: In the preceding example, we defined the identical method in the subclass and superclass. The goal
of method overriding is to provide a custom implementation of a subclass method. When we built the Boy subclass
object, it performed the subclass method, and printed Man is running instead of Human is running.
When we create an object of a parent class, the parent class method is always invoked.
Let’s look at another example in which we build two Classes called Colleges and Students, both of which have a
common function called void students details (). Let’s have a look at the following code.
Second example:
class Colleges{
// Declaring-variables
String names;
int rollnum;
// Overriden-Method
void stu_details(names,rollnum){
this.names = names;
this.rollnum = rollnum;
}
void display(){
print("Student name:${names}");
print("Student rollno: ${rollnum}");
print("Result is passed");
}
}
class Students extends Colleges{
// Overriding-Method
void stu_details(names,rollnum){
this.names = names;
this.rollnum = rollnum;
}
void show(){
print("Student name:${names}");
print("Student rollno: ${rollnum}");
print("The result is failed");
}
}
void main(){
//Creating object of subclass
Students st1 = new Students();
st1.stu_details("Josephin",121);
st1.show();
Explanation: In the above example, two classes are created: Colleges as a parent class and Students as a child
class. Both classes define the function stu details with identical parameters and return types.
The Students subclass now inherits the Colleges superclass, and the stu details() function is overridden in the
subclass.
We built a Students object and used appropriate inputs to call stu details(). It ran the subclass method and then
reported the outcome.
Similarly, we generated an object of the Colleges superclass object, executed its methods, and printed the
various outcomes.
class Humans{
//Overridden-method
void run()
{
print("The Human is running");
}
}
class Man extends Humans{
//Overriding method
void run(){
// Accessing Parent class run() method in child class
super.run();
print("The Boy is running");
}
}
void main(){
Man m1 = new Man();
//This will call child class version of eat()
m1.run();
}
Explanation: We used the super keyword to access the Humans class method in the child class in the preceding
example. We don’t need to instantiate the parent class anymore. We merely constructed the subclass object called
the run() methods of the child and parent classes.
Defining a Getter
The getters method may define by using the get keyword with no parameters and an appropriate return type.
Syntax:
return-type get field-name{
}
Defining a Setter
Using the set keyword, we may specify the setter method with one argument and no return type.
Syntax:
set field-name {
}
Example:
class Students {
String stdNames;
String branchs;
int stdAges;
// getter method
String get std_names
{
return stdNames;
}
void set std_names(String names)
{
this.stdNames = names;
}
void set std_ages(int ages) {
if(age> = 25){
print("The Student age should be greater than 25")
}else{
this.stdAges = ages;
}
}
}
int get std_ages{
return stdAges;
}
void set std_branchs(String branch_names) {
this.branchs = branch_names;
}
int get std_branchs{
return branchs;
}
}
void main(){
Students std1 = new Students();
std1.std_names = 'Johnini';
std1.std_age = 22;
std1.std_branch = 'Computer-Science';
print("The Student name is: ${std_names}");
print("The Student age is: ${std_ages}");
print("The Student branch is: ${std_branchs}");
}
Syntax:
abstract class Class-Name {
// Body of the abstract class
}
Abstract Class Usage
Assume we have a class Person with the function displayInfo() and two subclasses, Boy and Girl. Because each
person’s information differs from the other, there is no value to implementing displayInfo() in the parent class.
Because each subclass is required to override the parent class function with its implementation; as a result, we may
force the subclass to implement that method, which is one advantage of making the method abstract. The provided
implementation is not required in the parent class.
Example:
abstract class Persons {
//declaration of abstract method
Explanation: As we can see in the above code, we implemented the abstract method in two subclasses based on
its requirements, and then we invoked the displayInfo() function using the objects of both classes’ objects.
DART INTERFACES
An interface establishes the syntax that all entities must follow. Dart has no specific syntax for defining interfaces.
An interface is defined as a class in which an object may access any set of methods. The Class declaration has the
ability to interface with itself.
The term implement must be written followed by the class name to utilize the interface. The implementing class
must offer a thorough specification of all the interface’s functionalities. We may say that every function with the
body in the interface that we wish to achieve must be defined by a class.
Declaring an Interface
Dart does not offer syntax for explicitly declaring interfaces. A class declaration is implicitly an interface that
contains the whole instance member of the class and any interfaces it implements.
Implementing an Interface
Another class must implement the interface using the implements keyword to use interface methods. A class that
implements an interface must completely implement all the interface’s functions. The syntax of the implementing
interface is as follows.
Syntax:
class Class-Name implements Interface-Name
In the following example, we declare a class called Employees. The Engineers class implicitly implements the
interface definition for the Employees class.
class Employees
{
void display() {
print("Working as an engineer");
}
}
// Defining the interface by implanting another class
class Engineers implements Employees
{
void display() {
print("Engineer in this company");
}
}
void main()
{
Engineers eng1 = new Engineers();
eng1.display();
}
Explanation: In the preceding example, we defined the Engineers class as an interface that implements the
Engineers class. Then, in both classes, we defined the identical function display(). This method is overridden in the
class Engineers; therefore, we generated an Engineers object in a main() function that called the display() function.
It displayed the output on the screen.
Syntax:
class Class-Name implements interface1, interface2,…interface n
Example:
class Students
{
String names;
int ages;
void displayNames() {
print("I am ${names}");
}
void displayAges() {
print("My age is ${ages}");
}
}
class Faculty
{
String dep_names;
int salary;
void displayDepartment() {
print("I am a professor of ${dep_names}");
}
void displaySalary() {
print("Salary is ${salary}");
}
}
// Defining the interface by implementing another class
class Colleges implements Students, Faculty
{
// Overriding the Students class members
String names;
int ages;
void displayNames() {
print("I am ${names}");
}
void displayAges() {
print("My age is ${ages}");
}
//Overriding each data member of Faculty class
String dep_names;
int salary;
void displayDepartment() {
print("I am a proffesor of ${dep_names}");
}
void displaySalary() {
print("Salary is ${salary}");
}
}
void main()
{
College cg1 = new Colleges();
cg1.names = "Josph";
cg1.age = 22;
cg1.dep_name = "Computer Science";
cg1.salary = 52000;
cg1.displayNames();
cg1.displayAges();
cg1.displayDepartments();
cg1.displaySalary();
}
Explanation: Different interfaces were implemented in class colleges in the above example. Each data member of
the Student and Faculty classes has precedence in the Colleges class. We created a Colleges class object and called
the overriding functions. It printed the outcome.
DOI: 10.1201/9781003299363-4
IN THIS CHAPTER
Exceptions
Collections
Packages
Generators
Unity Testing
In the previous chapter, we discussed data functions, recursion, and object-oriented, where we also covered
inheritance, interfaces, constructor, and overriding. In this chapter, we will discuss exceptions, packages, libraries,
and html DOM.
DART EXCEPTIONS
Exceptions in Dart are runtime errors. It is triggered when the program is executed. When the program runs
internally, and the Dart compiler finds something inappropriate, the program does not communicate the problem at
build time. The application is then terminated unexpectedly after reporting a runtime error. Exceptions are the
name given to this sort of problem. For instance, a given integer is divided by zero, attempting to access entries
from an empty list.
Dart supports the built-in exceptions listed in the following table.
Sr. No. Exceptions Description
1. DefferedLoadException When a delayed library fails to load, this exception is raised.
2. FromatException The exception is the one that is thrown.
3. IntegerDivisionByZeroException When a number is split by zero, this error is thrown.
4. IOEException It is the most basic type of input-output exception.
5. IsolateSpawnException When an isolated cannot be generated, this exception is issued.
6. Timeout This exception is raised when a scheduling timeout occurs while waiting for an async result.
The exception’s primary goal is to manage the runtime issue and keep the program from ending unexpectedly. In
Dart, every exception is a subtype of the predefined class Exception. To handle exceptions, Dart supports the
following techniques.
Syntax:
try {
// the code that might throw an exception
}
on Exception1 {
// Specify exception
}
Catch Exception2 {
// the code for handling exception
}
Explanation: In the previous code, we defined three variables in the main () function: x, y, and res. We wrote the
suspect code in a try block and divided x by 0 to see whether an exception was thrown. When the try block
discovered the issue, control was moved to the on block, containing the code to handle the error. The program’s
execution was not stopped as a result of this.
Let’s look at an example that makes use of the catch block.
Finally Block
Whether or whether an exception occurs, the finally block is always executed. After the try/on/catch, it executes
unconditionally.
The syntax for the finally block is shown below.
Syntax:
try {
// the code that may be throw an exception
}
on Exception1 {
//the exception handling code or specifying the exception
}
catch Exception2 {
// the code for exception handling
}
finally {
// the code that should always execute; whether exception or not.
}
Example:
finally { void main() {
int a = 17;
int b = 0;
int rest;
try {
rest = a ∼/ b;
}
on IntegerDivisionByZeroException {
print('Cannot divide by zero');
}
Throwing an Exception
We have the option of raising an exception explicitly or forcefully. The expressly raised exception should handle to
keep the application from crashing. The syntax is shown below.
Syntax:
throw new Exception-name()
Example:
main() {
try {
check_marks(-20);
}
catch(e) {
print('Marks cannot be negative');
}
}
void check_marks(int marks) {
if(marks<0) {
throw new FormatException(); // Raising explanation externally
}
}
Custom Exceptions
As previously stated, each exception in Dart is a subtype of the built-in class Exception. Dart allows us to build
new exceptions by extending the current exception class. The syntax is shown below.
Example:
class AmntException implements Exception {
String expMsg() => 'Entered the Amount should be greater than zero';
}
void main() {
try {
withdraw_amnt(-1);
}
catch(E) {
print(E.expMsg());
}
finally {
print('Ending requested operation.....');
}
}
void withdraw_amt(int amnt) {
if (amnt <= 0) {
throw new AmntException();
}
}
Explanation: In the preceding example, we defined a custom exception called AmntException. If the entered
amount is outside of the acceptable range, the code throws an exception, and the function call is wrapped in a try…
catch block.
TYPEDEF IN DART
In Dart, the typedef function is used to create an alias for a function type, which we can then use as a type
annotation when creating variables and return types for that function type. As a type annotation in variable
declaration or function return type, an alias of function type can be used. When we assigned the function type to a
variable, we stored the type information in a typedef.
Declaring a Typedef
A typedef keyword is used to create an alias for a function identical to the actual function. A function prototype
with a set of arguments can likewise be created. The syntax is shown below.
Syntax:
typedef function-name(parameters)
Example: Let’s make an alias for MultiOperation(int a1, int a2) with two integer arguments.
typedef MultiOperation(int a1, int a2); // function signature
Let’s look at an example of defining two functions with the same signature as the MultiOperation.
Example:
Sum(int a1, int a2) {
print("Sum of the two number:${a1+a2}");
}
Sub(int a1, int a2 ) {
print("Subtraction of the two number:${a1-a2}");
}
Syntax:
var-name(parameter);
Example:
MultiOperation mop;
mop = Sum;
mop(30,20);
mop = Sub;
mop(20,10);
The mop variable is a typedef variable that can refer to any method that accepts two integer parameters. Using
typedefs, the function reference can alter at runtime.
Explanation: We established an alias for the MultiOperation() method in the preceding code using the typedef
keyword. We added two new functions, Sum() and Sub(), with the same signature as the typedef function.
Then we added the typedef variable mop, referencing both the Sum() and Sub() methods. We then called the
function, handing it the necessary parameter, and printed the result.
Typedef as Parameter
As a parameter, we may use the typedef method. In the following example, we add a NumericOperation(int a1, int
a2, MultiOperation mop) function to the same program, using the two integer variables and typedef
ManyOperation mop as its parameter.
Example:
typedef MultiOperation(int num1, int num2); // typedef function signature
Sum(int a1, int a2) {
print("Sum of the two number:${a1+a2}");
}
Sub(int a1, int a2 ) {
print("Subtraction of the two number:${a1-a2}");
}
NumericOperation(int a1, int a2, MultiOperation mop){
print("Inside Operation");
mp(a1,a2);
}
void main() {
print("DartTpoint - Dart typedef Example");
NumericOperation(30, 20, Sum);
NumericOperation(30, 20, Sub);
}
We didn’t need to establish a typedef variable to refer to each method in the above code; we just invoked the
NumericOperation() function, passing the required value and the typedef variable mop. It carried out the specified
actions and printed the result.
Debugging in Dart
Debugging is the process of finding and removing current and potential problems in a Dart program that may
generate ambiguity and uncertainty during program execution. Debugging is required to find and fix errors for the
program to execute smoothly or without interruption.
When we use the Dart IDE, debugging becomes much more accessible. We will assume that we have installed
the most common and appropriate IDE WebStorme on our system. The WebStorm Editor allows us to debug in
stages.
METADATA IN DART
Dart Metadata is used to provide more information to the Dart program. It often begins with @ symbol, followed
by a reference to a compile-time constant or a call to a constant constructor.
library students;
Class Students {
final String studentNames;
final String rollnum;
const Students(this.studentNames, this.code);
}
Metadata in Dart is often defined before a library name, class, typedef, field, type parameter, factory, function,
constructor, parameter, or variable declaration and before an import or export directive. In runtime, we may access
the metadata by utilizing reflection.
Let’s have a look at an example:
class Humans{
@Overridden method
void run()
{
print("Humans are running");
}
}
class Men extends Humans{
@Overriding method
void run(){
print("The Boys are running");
}
}
void main(){
Men m1 = new Men();
//This will call child class version of run()
m1.run();
}
COLLECTION IN DART
Unlike the other programming languages, Dart does not offer arrays for data storage. We may use the Dart
collection for the array data structure. Using the dart::core library, we may activate the collection’s additional
classes in our Dart script.
Dart collection may be divided into the following categories:
Dart
Description
Collection
List A list is a collection of an ordered collection of collections. The list class in the dart::core library allows us to construct and edit lists. It offers
the following kinds of list:
Fixed Length List – We cannot adjust the length of the list during runtime.
Growable List – We can adjust the list’s length at runtime.
Set A set is a collection of items that each object can define at the same time. To access the dart::core library’s facilities, use the Set class.
Maps The maps are a collection of key-value data pairs. Each value is associated with a particular key. In the dart, the key and value can be of any
type. A map is a living collection. We may claim that the map can change at runtime. To deal with it, the dart::core library provides the Map
class.
Queue A queue is a collection of locations stored in the first-in-first-out (FIFO) order. It can adjust on both ends. We may add the element from one
end and delete it from the other.
Collections Iteration
The iterator class in the dart::core library allows for simple collection traversing. Every collection has an iterator
property, as we all know. This property produces an iterator containing a list of the collection’s items.
Example:
import 'dart:collection';
void main() {
Queues ques = new Queues();
ques.addAll([20,30,40]);
Iterator c= ques.iterator;
while(c.moveNext()) {
print(c.current);
}
}
Explanation: The moveNext() method in the preceding code returns a Boolean value indicating the following
entry. The current property returns the object to which the iterator is presently pointing.
DART GENERICS
Dart Generics are identical to Dart collections, used to hold homogeneous data. Dart is an optionally typed
language, as described in the features section.
Dart Collections are heterogeneous by default. To put it another way, a single Dart collection may store the
values of many data types. On the other hand, A Dart collection can store homogeneous items or values of the
same kind.
Dart Generics allows us to impose a constraint on the data type of the collection’s values. These collections are
known as type-safe collections.
Dart programming has a unique feature called type safety, which ensures that a memory block may only hold
data of a specified data type.
Generics are a means for all Dart collections to allow type-safety implementation. The angular bracket pair is
used to declare the type-safe collection. The data-types of the collection are included within the angular bracket.
The syntax is shown below.
Syntax:
Collection-name <data_type> identifier = new
Collection-name<data_type>
We can type-safe implement numerous Dart objects like List, Queue, Map, and Set. It is also supported by all
implementations of the collection types defined above.
Explanation: We generated a type-safe list and added a string entry using the add() method.
If we try to insert a value other than the one specified, we will get a compilation error. Let’s have a look at an
example:
void main() {
List <String> logStrs = new List <String>();
logStrs.add(511); // Add integer value
logStrs.add("Info");
logStrs.add("Error");
//iterating across list
for (String c in logTypes) {
print(c);
}
}
Example: The Generic Set
void main() {
Set <int>numberSets = new Set<int>();
numberSets.add(29);
numberSets.add(32);
numberSets.add(41);
numberSets.add(54);
numberSets.add(60);
// numberSets.add("");
// compilation error;
print("The Default implementation :${numberSets.runtimeType}");
for(var c in numberSets) {
print(c);
}
}
Generic Map
As we all know, declaring a map necessitates using a key and a value. The syntax is shown below.
Syntax:
Map <Key-type, value-type>
Example:
void main() {
Map <String, String>m1={'name':'Josen','Rollno':'Std1201'};
print('Map :${m1}');
}
PACKAGES IN DART
Dart packages are collections of well-organized, self-contained, and reusable code units. Third-party libraries or
packages may need the use of applications. Along with the generated program and sample data, the package often
comprises a collection of classes, functions, or units of code for specialized purposes. Dart has many default
packages that are loaded automatically when the dart console is launched. However, if we require packages other
than the default packages, we must install and load them manually to utilize them. When a package is loaded, it is
available for usage throughout the Dart environment.
name: 'vector_victor'
version: 0.0.1
description: An absolute bare-bones web app.
...
dependencies: browser: '>=0.10.0 <0.11.0'
The Dart IDE includes built-in support for utilizing the pub, including building, downloading, updating, and
publishing packages. Alternatively, we may use the pub command line. The following is a collection of some of
the most significant pub commands.
Sr. No. Description
pub get It is used to obtain all application-dependent packages.
pub upgrade It is used to update all application dependencies up to date.
pub build It is used to develop our web application, and it will generate a build folder including all necessary scripts.
pub help It is utilized to obtain help with all pub commands or get stuck while programming.
pub get
This command will download the package to the application directory’s packages folder.
Example:
name: TestApp
version: 0.0.1
description: A simple dart application
dependencies:
xml:
The xml has been added to the project dependencies. By importing the Dart XML package, we can now utilize it in
the project. It is possible to import it as follows:
Syntax:
xml. parse(String input):
<book>
<title lang = "English">The Drake </title>
<price>80.00</price>
</book>
<price>300.00</price>
</bookstore>''';
LIBRARIES IN DART
The library in Dart is a collection of routines or sets of programming instructions. Dart has several built-in libraries
that are useful for storing routines (functions, classes, etc.) and are often used. A Dart library comprises constants,
functions, properties, exceptions, typedefs, and a collection of classes.
Importing a Library
We must first import it into the current program to use the library. The import keyword is provided by Dart and is
used to make the library available in the existing file. Multiple libraries can use in a single file.
Dart built-in library URIs, for example, are used as a dart scheme to refer to a library. Other libraries can define
their URIs utilizing a file system path or the package: scheme. Dart’s package manager pub offers libraries and
employs the package scheme.
The followings are descriptions of several widely used libraries.
Sr.
Library Description
No.
1. dart:io This library provides server applications with File, HTTP, socket, and other I/O functionality. This library is not intended for use in
browser-based applications. We don’t need to import it because it is imported by default explicitly.
2. Dart:core This library contains collection, built-in types, and other essential dart application functionality. It is automatically imported.
3. Dart: math This library includes a variety of mathematical functions, constants, and a random number generator.
4. Dart: It is used in encoders and decoders to convert various data formats such as JSON and UTF.
convert
5. Dart: It represents lists that efficiently hold fixed-sized data (for example – unsigned 8-byte integer).
typed_data
Explanation: We imported the built-in library ‘dart:math’ in the preceding code. It has several built-in
mathematical functions; in this case, we utilized the sqrt() function with a number. It accepts an integer as an input
and determines its square root. We gave an integer number of 25 to the sqrt() method, and it returned a value of 5.
Library Encapsulation
Dart allows us to encapsulate or restrict access to the dart library’s content. It is possible to use the _ (underscore)
followed by the identification. The _ (underscore) character makes the library’s content fully private. The syntax is
shown below.
Syntax:
_identifier
Example:
library Greetings;
// We define function using the _underscore as a prefix.
void _sayHi(msg) {
print("We access this method in another:${msg}");
}
The above file is saved as greetings.dart, let’s import the library now.
import 'greetings.dart' as w;
void main() {
w._sayHi("Hello DartTpoint");
}
Syntax:
library library_name
// go here library contents
import 'library_name'
import 'dir/library_name'
library calculator_simple;
import 'dart:math';
//the library content
int add(int numb1,int numb2){
print("inside add method of the calculator_simple Library ") ;
return numb1+numb2;
}
int multiplication(int numb1,int numb2){
print("inside multiplication method of the calculator_simple Library ") ;
return numb1*numb2;
}
int subtraction(int numb1,int numb2){
print("inside subtraction method of the calculator_simple Library ") ;
return numb1-numb2;
}
int modulus(int numb1,int numb2){
print("inside modulus method of the calculator_simple Library ") ;
return numb1%numb2;
}
Now we import the aforementioned custom file into the current file, ‘library.dart.’
import 'calculator.dart';
void main() {
var nu1 = 40;
var nu2 = 30;
var sum = add(nu1,nu2);
var mod = modulus(nu1,nu2);
var mul = multiplication(nu1,nu2);
var div = divide(nu1,nu2);
var sub = subtraction(nu1,nu2);
print("$nu1 + $nu2 = $sum");
print("$nu1 % $nu2= $mod");
print("$nu1 + $nu2 = $mul");
print("$nu1 - $nu2 = $sub");
}
Syntax:
import 'library_uri' as prefix
Example:
To begin, let us define a library: greeting. dart
library greetings;
void sayHi(msg){
print("Learn Dart with ${msg}");
}
library hellogreetings;
void sayHi(msg){
print("${msg} provides tutorials on all technical topic");
}
import 'greetings.dart';
import 'hellogreetings.dart' as gret;
GENERATORS IN DART
Dart Generator is a one-of-a-kind function that generates a series of values. Generators return values on demand,
which implies that the value is created when we attempt to iterate through iterators. Dart includes support for two
types of generator functions.
Synchronous Generators
Asynchronous Generators
Synchronous Generator
It returns an iterable object that synchronously carries value. The yield keyword is used in combination with the
synchronous generator function body being marked as sync* to generator values.
Let’s have a look at an example of a synchronous generator:
main() {
print("the Dart Synchronous Generator Example.");
oddNumber(20).forEach(print);
}
// syn* functions returns an iterable
Iterable<int> oddNumber(int numb) sync* {
int x = numb;
while(x >= 0) {
if(x%2 == 1) {
// 'yield' statement
yield x;
}
x--;
}
}
Explanation: We defined an oddNumber(20) function in the preceding program and used a foreach loop with no
body. The foreach loop will iterate through the function. As a synchronous generator function, we now created the
oddNumber(20) function.
We created a new variable k in the function body, assigning the input n. Then, to iterate the function, we used a
while loop, and the loop body is iterated until the value of x is less than or equal to 0.
To obtain the odd numbers from the generators, we used the modulus operation on x. We used the yield
statement, which stops the function and returns the value one at a time. It will return the value of each generator
function run. When the while loop’s condition turns false, the loop is ended, and the odd numbers are printed.
Asynchronous Generators
It returns a stream object that transmits data asynchronously. The yield keyword is used in combination with the
async* to generator values indication of the asynchronous generator function body.
Example:
main() {
print("The Dart Asynchronous Generator Example.");
asyncNaturalsTo(20).forEach(print);
}
// async* functions returns an stream object
Stream<int> asyncNaturalsTo(int numb) async* {
int x = 0;
while(x < numb) {
// 'yield' statement
yield x++;
}
x--;
}
Explanation: The values in the preceding code were created asynchronously. In each function body execution, the
asyncNaturalsTo(int numb) method returns a stream object. In this case, the yield keyword acted similarly to the
previous example: it stopped the function’s execution, returned the value, and restarted its execution for the next
iteration. It will keep happening till the function body is finished.
void main() {
print('creating-iterator');
Iterable<int> numbers = getNumbers(5); // Here we are creating iterator
print('Iteration starts');
for (int x in numbers) {
print('$x'); // Iterate over the iterator
}
print('end of the main function');
}
Iterable<int> getNumbers(int nm) sync* { // define generator synchronously
print('generator started');
for (int x = 0; x < nm; x++) {
yield x;
}
print('generator function ended');
}
Explanation: When we iterate through the iterator, the above generator function generates the value.
void main() {
print('creating-iterator');
Stream<int> numbers = getNumbers(5);
print('starting to listen');
numbers.listen((int m) {
print('$m');
});
print('end of main function');
}
Stream<int> getNumbers(int number) async* { // declaring the asynchronous generator function
print('waiting inside generator a 3 seconds :)');
await new Future.delayed(new Duration(seconds: 4)); //sleep 3s
print('started generating values...');
for (int x = 0; x < number; x++) {
await new Future.delayed(new Duration(seconds: 2)); //sleep 1s
yield x;
}
print('ended generating values');
}
Example:
class Students {
String call(String names, int ages) {
return('The Student name is $names and Age is $ages');
}
}
void main() {
Students stu1 = new Students();
var msgs = stu1('Shreya',19); // Class instance called like a function.
print('Dart Callable class');
print(msgs);
}
Explanation: In the above code, we defined a call() function in the Student class that accepts two parameters.
Return a message with the string name and integer age. Then we built an object of class Student and called it as if
it were a function.
class Employees {
int call(int empid, int ages) {
return('Employee id is ${empid} and Age is ${ages}');
}
}
void main() {
Student stu1 = new Students();
Employees emp1 = new Employees();
var msgs = stu1('peterin',19); // Class instance called like a function.
var msgs2 = emp1(102,33); // Class instance called like a function.
print('Dart Callable class');
print(msgs);
print(msgs2);
}
Explanation: We defined two callable functions in Students and Employees classes in the preceding code. The
call() method of the Employees class takes two parameters: String empid and int ages. Instances of both types were
referred to as callable functions.
DART ISOLATES
Dart supports asynchronous programming, which allows us to run our application without being blocked. To
accomplish concurrency, asynchronous programming is employed. Dart isolation is a thread variant. However,
there is a significant difference between the standard implementations of “Thread” and “Isolates.” When compared
to Thread, the isolate performs differently. The isolates are self-contained workers that do not share memory and
instead communicate by sending messages through channels. Because isolation completes its operation by passing
messages, it requires a method to serialize a message.
Message passing is used to communicate between the isolates as a client and server. It enables the software to
make use of multicore microprocessors right away.
Dart has the dart:isolate package, which we may use to implement the isolate in our application. It provides a
way for taking single-threaded Dart code and enables applications to make better use of the available hardware.
First example:
import 'dart:isolate';
void sayhi(var msgs){
print('execution..the message is :${msgs}');
}
void main(){
Isolate.spawn(sayhi,'Hello!!');
Isolate.spawn(sayhi,'Whats up!!');
Isolate.spawn(sayhi,'Welcome!!');
print('execution from the main1');
print('execution from the main2');
print('execution from the main3');
}
Explanation: In the preceding example, the isolate class’s spawn method performed a function sayhi in parallel
with the other code. It requires two arguments.
The function to be spawned and the string to be provided to the spawned function.
We have two functions, sayhi() and main(), which may not be executed in the same sequence each time. If we
run the same program repeatedly, the outcome will be different, as seen in the second output.
Second example:
void start() async {
ReceivePort receiverPorts = ReceiverPort(); // Port for the isolate to receive messa
isolate = await Isolate.spawn(runTimer, receiverPort.sendPort);
receivePorts.listen((data){
stdout.write('Receiving: '+ data + ', ');
});
}
void runTimer(SendPort, sendPort) {
int counts = 0;
Timer.periodic(new Duration(seconds: 2), (Timer t) {
counts++;
String msgs = 'notification ' + counts.toString();
stdout.write('Sending: ' + msgs + ' -');
sendPort.send(msgs);
});
}
Explanation: In the preceding code, we defined an asynchronous function start() that generates a port and spawns
an isolation. We marked the start method as async to wait for the response from the isolate spawning and keep a
reference to the new isolate. It is critical if we are to eliminate the running isolated. We gave two parameters to the
spawn() method: the first parameter runTimer, which is a callback function that will use to execute runTimer(), and
the second parameter sendPort, which is also a callback function that will use to send a message back to the caller.
The start() function begins the receiverPort listening for messages from isolation. When it receives the message, it
will print it to the console.
Stop an Isolate
The kill() function in the dart: isolates package terminates a running isolate.
Example:
void stop() {
If (isolate != null) {
stdout.writeln('Stopping-Isolate');
isolate.kill(priority: Isolate.immediate);
isolate = null;
}
}
Explanation: We defined a stop() function that destroys the currently running isolation and sets its reference to
null in the preceding example. We set the priority of the isolate to immediate, which means that the isolate will be
terminated as soon as possible.
Complete Program
import 'dart:io';
import 'dart:async';
import 'dart:isolate';
Isolate isolate1;
// Start isolate
void start() async {
ReceivePort receiverPort1 = ReceiverPort(); // Port for isolate to receive message.
isolate1 = await Isolate.spawn(runTimer, receiverPort1.sendPort);
receivePort1.listen((data){
stdout.write('Receiving: '+ data + ', ');
});
}
void runTimer(SendPort, sendPort) {
int count = 0;
Timer.periodic(new Duration(seconds: 2), (Timer t) {
count++;
String msgs = 'notification ' + count.toString();
stdout.write('Sending: ' + msgs + ' -');
sendPort.send(msgs);
});
}
ASYNC IN DART
Dart Async is a programming construct that is linked to asynchronous programming. The asynchronous operation
is carried out in a thread. It guarantees that the key duties are carried out until they are completed. The
asynchronous action is carried out independently of the main program thread. In Dart, one operation cannot
interrupt another; this implies that only one operation may run at a moment when no other component of the
program can stop it. Let’s have a look at an example:
import 'dart:io';
void main() {
print("Enter favorite car :");
// prompt for the user input
String cars = stdin.readLineSync();
// this is a synchronous method that reads user input
print("The car is ${cars}");
print("End of the main");
}
Explanation: We utilized the synchronous readLineSync() function in the preceding code. It implies that until the
readLineSync() function completes its execution, the execution of any instructions that follow will be halted.
The stdin.readLineSync () function does nothing until it receives user input. It waits for human input before
proceeding with the execution.
Example:
import "dart:async";
import "dart:io";
void main(){
File files1 = new File("C:\Users\DEVANSH SHARMA\Desktop\contact.txt");
Future<String> fs = files1.readAsString();
// returns a future object, it is an async method
fs.then((data)=>print(data));
// once file is read, call back method is invoked
print("End of the main");
}
Dart Future
The Dart Future is defined as receiving a result at some point in the future. The Future object is used to make
asynchronous programming more accessible. Future objects are used to represent values returned by an expression
whose execution will be completed later (in future). We can utilize async and await or the Future API to interact
with the future.
Syntax:
func_name() async {
//function-body
}
When an async function is called, the Future object returns immediately, indicating that the async function will
execute later. The function call returned the Future object after the async function’s body was run. The function
call will finish with the outcome of the function call.
Here, e is an asynchronous expression intended to evaluate a Future in this case. The await statement evaluates e
before suspending the current function until the result is ready.
Example:
void hi() async {
print("Hi DartTpoint");
}
void main() async {
await hi(); // Using the await keyword
print("Task Completed");
}
Explanation: We used the async keyword to make the main() function asynchronous since we run the hi() method
asynchronously. Then, we used the await modifier to call hi(), which executed asynchronously.
Example:
import 'dart:isolate';
void sayhi(var msg){
print('execution from sayhi and the message is :${msg}');
}
void main(){
Isolate.spawn(sayhi,'Hello');
Isolate.spawn(sayhi,'How are you?');
Isolate.spawn(sayhi,'Welcome');
print('execution from the main1');
print('execution from the main2');
print('execution from the main3');
}
Prepare
Review
Rework
Baseline
Prepare
Review
Rework
Baseline
Unit Test
Perform
Right-click the pubspec.yaml file and select Pub: get dependencies. This will include the installation of the
“test” package in our project.
We may also use the following command to install it.
pub get
import "package:test/test.dart";
test("Test Description", () {
expert(actualValue, matchingValue)
});
Syntax:
group("Test_Group_Name", () {
test("test_case_name_1", () {
expect(actual, equals(exptected));
});
test("test_case_name_2", () {
expect(actual, equals(expected));
});
})
import 'package:test/test.dart';
// Importing test package
int add(int a,int b)
// this function to be tested {
return a+b;
}
void main() {
// Defining test function
test("test to check the add method",(){
// Arrange
var expected = 40;
// Act
var actual = add(20,30);
// Asset
expect(actual,expected);
});
}
import 'package:test/test.dart';
int add(int a,int b){
return a+b;
}
int sub(int a,int b){
return a-b-1;
}
void main(){
test('test to check sub',(){
var expected = 20;
// Arrange
var actual = sub(40,30);
// Act
expect(actual,expected);
// Assert
});
test("test to check add method",(){
var expected = 40;
// Arrange
var actual = add(20,10);
// Act
expect(actual,expected);
// Asset
});
}
In the above example, the add() method passed the unit test, but the sub() function failed owing to a logical
mistake.
import "package:test/test.dart";
void main() {
group("String", () {
// First test case
test("testing on split() method of string class", () {
var string = "Hii,Helloo,Heyy";
expect(string.split(","), equals(["Hii", "Helloo", "Heyy"]));
});
// Second test case
test("testing on trim() method of string class", () {
var string = " Helloo ";
expect(string.trim(), equals("Helloo"));
});
});
}
Objects of DOM.
Using the dart:html library, we can control objects and elements in the DOM. The dart:html library cannot be
used in a console application. In order to deal with the HTML library in the web application, we must import the
dart:html package.
import ’dart.html’;
The querySelector() method returns the first element that matches the selector’s provided group.
Syntax:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width, initial-scale = 1.5">
<meta name = "scaffolded-by" content = "https://github.com/google/stagehand">
<title>DemoWebApp</title>
<link rel = "stylesheet" href = "styles.css">
<script defer src = "main.dart" type = "application/dart"></script>
<script defer src = "packages/browser/dart.js"></script>
</head>
<body>
<h1>
<div id = "output"></div>
</h1>
</body>
</html>
Main.dart
import 'dart:html';
void main() {
querySelector('#output').text = 'Our Dart web dom app is running';
}
Event Handling
The onClick event for DOM Elements is provided by the dart:html library. The syntax demonstrates how an
element may handle a series of click events.
querySelector('#Id').onClick.
listen(eventHanlderFunction);
OnClick, the querySelector() method returns the element from the specified DOM. Listen() will accept an
eventHandler method, which will be called when a click event occurs. The syntax of eventHandler is as follows:
TestEvent.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width, initial-scale = 1.5">
<meta name = "scaffolded-by" content ="https://github.com/google/stagehand">
<title>DemoWebApp</title>
<link rel = "stylesheet" href = "styles.css">
<script defer src = "TestEvent.dart" type="application/dart"></script>
<script defer src = "packages/browser/dart.js"></script>
</head>
<body>
<div id = "output"></div>
<h1>
<div>
Enter you name : <input type = "text" id = "txtName">
<input type = "button" id = "btnWish" value="Wishs">
</div>
</h1>
<h2 id = "display"></h2>
TestEvent.dart
import 'dart:html';
void main() {
querySelector('#btnWish').onClick.listen(wishHandler);
}
void wishHandler(MouseEvent event){
String name = (querySelector('#txtName') as InputElement).value;
querySelector('#display').text = 'Hello'+ name;
}
CHAPTER SUMMARY
In this chapter, we discussed exceptions in Dart, typedef, collections, packages, and libraries. Moreover, we also
discussed callable classes, async, unit testing, and html DOM.
CHAPTER 5
Basics of Flutter
DOI: 10.1201/9781003299363-5
IN THIS CHAPTER
Flutter Widgets
Layouts and Gestures
State Management
Details of Flutter Widgets
In the previous chapter, we covered advanced topics in Dart such as collection, typedef, libraries, generators, and
unit testing. In this chapter, we will discuss flutter widgets, layouts, gestures. Moreover, we will also discuss state
management, Flutter IDE, and all flutter widgets in detail.
Step 5: In the next wizard, enter the company domain name and click the Finish button.
After pressing the Finish button, it will take some time to construct a project. We will have a fully functional
Flutter application with limited functionality when the project is finished.
Step 6: Let’s look at the structure and purpose of the Flutter project application. The many folders and
components of the Flutter application structure are:
.idea: This folder is at the top of the project structure and contains the Android Studio setup. It makes no
difference because we are not going to utilize Android Studio; thus, the contents of this folder may be
ignored.
.android: This folder contains a whole Android project needed for building the Flutter application for
Android. When the Flutter code is turned into native code, it is injected into this Android project,
resulting in a native Android app. When we use the Android emulator, this Android project is used to
develop the Android app, which is then published to the Android Virtual Device.
.ios: This folder contains a complete Mac project and is used for building the Flutter app for iOS. It is
identical to the android folder used when designing an Android app. When the Flutter code is turned into
native code, it is injected into this iOS project, yielding a native iOS application. Building a Flutter
application for iOS is only feasible while using macOS.
.lib: This is an important folder that stands for the library. It is a folder where we will do 99 percent of
the project work. The Dart files that comprise the code for our Flutter application can be found in the lib
folder. This folder contains the file main.dart by default, which is the Flutter application’s entrance file.
.test: This folder includes Dart code developed for the Flutter application to run automated tests when
the app is built.
In the Flutter application, we may also have specific default files. In 99.99 percent of circumstances, we
do not manually touch these files. These are the files:
.gitignore: This is a text file that contains a list of files, file extensions, and directories that notify Git
which files in a project should be ignored. Git is a version-control file used to monitor source code
changes during software development.
.metadata: It is a file created automatically by the flutter tools and is used to monitor the attributes of
the Flutter project. This file handles internal activities, so we never have to modify the content manually.
.packages: It is a file created by the Flutter SDK that contains a list of dependencies for our Flutter
project.
Flutter demoapp.iml: It is always titled after the Flutter project name and contains different project
settings. This file handles internal operations controlled by the Flutter SDK, so you never have to modify
the content yourself.
pubspec.yaml: This is the project’s configuration file, which will be used often while working with the
Flutter project. It enables you to control how your application functions. This file contains the following:
General project parameters include the project’s name, description, and version.
Dependencies in the project.
Assets for the project (e.g., images).
pubspec.lock: It is a file created automatically depending on the.yaml file. It has a more detailed setup
of all requirements.
README.md: This is an auto-generated file that contains project information. If we wish to share
information with the developers, we may update this file.
Step 7: Open the main.dart file and replace the following code with it.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// This widget is root of our application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello Everyone Flutter Application',
theme: ThemeData(
// This is theme of your application.
primarySwatch: Colors.blue,
),
home: HomePage(title: 'Homepage'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is home page of our application.
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: Text('Hello Everyone'),
),
);
}
}
FLUTTER ARCHITECTURE
This section goes through the architecture of the Flutter framework. The Flutter architecture is made up of four
primary components.
Flutter Engine
Foundation Library
Widgets
Design Specific Widgets
Flutter Engine
The Flutter Engine is a portable runtime for high-quality mobile apps mostly built on the C++ programming
language. It includes animation and graphics, file and network I/O, plugin architecture, accessibility support, and a
dart runtime for writing, constructing, and executing Flutter applications. Google’s open-source graphics package,
Skia, is used to produce low-level visuals.
Foundation Library
The Foundation Library provides all of the packages necessary for the basic building blocks of constructing a
Flutter application. These libraries are written in the Dart programming language.
Widgets
Everything in Flutter is a widget, the framework’s primary notion. In Flutter, a widget is a user interface (UI)
component that impacts and controls the app’s display and interface. It is an immutable description of a portion of
the UI that contains graphics, text, shapes, and animations made with widgets. The widgets are similar to React
components.
Gestures
It is a widget in Flutter that offers interactivity (how to listen for and respond to gestures) by utilizing
GestureDetector. GestureDector is an invisible widget that interacts with its child widget via tapping, dragging,
and scaling. Combining with the GestureDetector widget can also add more interactive elements into the current
widgets.
State Management
The StatefulWidget widget in Flutter is used to keep the widget’s state. When its internal state changes, it is always
re-rendered. The re-rendering is optimized by measuring the distance between the old and new widget UIs and
rendering the necessary modifications.
Layers
Layers are a key notion in the Flutter framework, classified into several categories based on complexity and
organized in a top-down manner. The highest layer is the application’s UI, unique to the Android and iOS
platforms. All of the Flutter native widgets are located on the second-highest layer. The rendering layer comes
next, responsible for rendering everything in the Flutter app. The layers then fall to Gestures, the foundation
library, the engine, and the core platform-specific code.
FLUTTER WIDGETS
This part looks at the notion of a widget, how to make one, and the many types accessible in the Flutter
framework. We already know that everything in Flutter is a widget.
Flutter is simple to grasp if you are familiar with React or Vue.js.
Every time we write code in Flutter, it will be within a widget. The main goal is to create an app consisting of
widgets. It specifies how your app’s view should appear in its current setup and state. When we modify the code,
the widget rebuilds its description by calculating the difference between the previous and current widgets to
identify the minimal modifications for rendering in the app’s UI.
To construct the app, widgets are nested with one another. It signifies that your app’s root is a widget, and
everything underneath it is also a widget. A widget, for example, can show things, define design, manage
interaction, and so on.
The widget tree is depicted graphically in the following figure.
Tree of widget.
WIDGET TYPES
The Flutter widget may be divided into two categories:
Visible (Output and Input)
Invisible (Layout and Control)
Visible Widget
The visible widgets are connected to the data entered and output by the user. This widget comes in a variety of
forms, some of which are as follow:
Text
A Text widget contains text that will show on the screen. We may align the text widget by using the textAlign
property, and the style property allows us to customize the text by changing the font, font weight, font style, letter
spacing, color, and many other things. We may utilize it in the following code snippets.
new text (
'Hello, Dartpoint!',
textAlign: TextAlign.center,
style: new TextStyle(fontWeight: FontWeight.bold),
)
Button
This widget allows us to perform a specific action with a single click. Flutter does not support the Button widget
natively; instead, it employs buttons like the FlatButton and the RaisedButton. We may utilize it in the following
code snippets.
// Example of FlatButton
new FlatButton(
child: Text("Clickhere"),
onPressed: () {
// Do something here
},
),
// Example of RaisedButton
new RaisedButton(
child: Text("Clickhere"),
elevation: 4.0,
onPressed: () {
// Do something here
},
),
The onPressed property in the above example lets us to conduct an action when you click the button, and the
elevation property is used to adjust how much it stands out.
Image
This widget contains an image that may be retrieved from various sources, including the asset folder or straight
from the URL. It has many constructors for loading images, which are listed below:
image: It is a generic image loader that ImageProvider uses.
asset: It loads images from your project’s asset folder.
file: It reads pictures from the system’s folder.
memory: It loads the image from memory.
network: It retrieves photos from the network.
To include a picture in the project, first establish an assets folder to store your images, and then add the following
line to the pubspec.yaml file:
assets:
- assets/
Image.asset('assets/comp.png')
In the hello everyone example, the complete source code for inserting an image is displayed below:
Icon
This widget serves as a container for the Icon in Flutter. The following code describes it in further detail.
new Icon(
Icons.add,
size: 35.0,
)
Invisible Widget
The invisible widgets are associated with widget layout and control. It allows us to change how the widgets behave
and appear on the screen. Among the most critical sorts of these widgets are as follow:
Column
A column widget is a widget that arranges all of its children’s widgets vertically. It uses the mainAxisAlignment
and crossAxisAlignment attributes to establish space between widgets. The major axis in these attributes is the
vertical axis, while the cross axis is the horizontal axis.
Row
Row widget is similar to the column widget in that it builds a widget horizontally rather than vertically. In this
case, the horizontal axis is the primary axis, while the vertical axis is the cross axis.
Example: The following code lines create two widget items horizontally.
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
childrens: <Widget>[
new Text(
"Veg-Element",
),
new Text(
"Nonveg-Element"
),
],
),
Center
This widget is used to center the child widget that is contained within it. The center widget is present in all of the
preceding examples.
Example:
Center(
child: new clumn(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
childrens: <Widget>[
new Text(
"Veg-Element",
),
new Text(
"Nonveg-Element"
),
],
),
),
Padding
This widget covers other widgets to provide padding in specific directions. Padding can also provide in all
directions. We can see this in the example below, which shows a text widget with a padding of 5.0 in all directions.
Padding(
padding: const EdgeInsets.all(5.0),
child: new Text(
"Element 1",
),
),
Scaffold
This widget offers a framework for adding standard material design features such as AppBar, Floating Action
Buttons, Drawers, and so on.
Stack
This is a necessary widget mainly used to overlap a widget such as a button on a background gradient.
StatefulWidget
A StatefulWidget keeps information of its current state. It primarily consists of two classes: the state object and the
widget. It is dynamic because the inside data might change over the widget’s lifespan. This widget lacks a build()
function. It provides a method called createState() that returns a class that extends the Flutters State Class.
Checkbox, Radio, Slider, InkWell, Form, and TextField are instances of StatefulWidget.
Example:
class Cars extends StatefulWidget {
const Cars({ Key key, this.title }) : super(key: key);
@override
_CarState createState() => _CarState();
}
class _CarState extends State<Cars> {
@override
Widget build(BuildContext context) {
return Container(
color: const Color(0xFEEFE),
childs: Container(
childs: Container( //childs: Container() )
)
);
}
}
StatelessWidget
The StatelessWidget has no state information. Throughout its existence, it stays static. Text, Row, Column,
Container, and so on are instances of StatelessWidget.
Example:
class MyStatelessCarsWidget extends StatelessWidget {
const MyStatelessCarsWidget ({ Key key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(color: const Color(0x0xFEEFE));
}
}
FLUTTER LAYOUTS
The widget is the layout mechanism’s central notion. We know that Flutter treats everything as if it were a widget.
So your app’s picture, icon, content, and even its layout are all widgets. Some of the items we don’t see on our
app’s UI, such as rows, columns, and grids that arrange, constrain, and align the visible widgets, are also widgets
in this case.
Flutter allows us to design more sophisticated widgets by assembling numerous widgets. For example, consider
the following image, which has three symbols, each with a label beneath them.
share
route
call
The visual layout of the above image may be seen in the following figure that depicts a row of three columns,
each with an icon and label.
Layout of Flutter.
The container in the above image is a widget class that configures the child widget. It is mainly used to create
borders, padding, margins, background color, and various other features. The text widget is placed beneath the
container for adding margins in this case. In addition, the entire row is enclosed in a container to add margin and
padding around the row. Additionally, characteristics like color, text style, and so on are used to manage the
remainder of the UI.
Layout a Widget
Let’s look at how to make and show a simple widget. The following instructions demonstrate how to layout a
widget:
Step 1: First, we must choose a Layout widget.
Step 2: After that, create a visible widget.
Step 3: Finally, add the visible widget to the layout widget.
Step 4: Finally, add the layout widget to the page where you want the widget to appear.
Container
The most common layout widget, it offers adjustable choices for widget painting, positioning, and sizing.
Center(
child: Container(
margin: const EdgeInsets.all(14.0),
color: Colors.yellow,
width: 48.0,
height: 48.0,
),
)
Padding
It is a widget that is used to organize its child widgets based on the padding specified. It includes EdgeInsets and
EdgeInsets.fromLTRB for the specified side where padding is wanted.
const Greetings(
child: Padding(
padding: EdgeInsets.all(13.0),
child: Text('Hello Dartpoint!'),
),
)
Center
With this widget, we may center the child widget within itself.
Align
It is a widget that aligns its child widget inside itself and sizes is dependent on the size of the child. It gives more
control to place child widget exactly where we want it.
Center(
child: Container(
height: 120.0,
width: 120.0,
color: Colors.black,
child: Align(
alignment: Alignment.topRight,
child: FlutterLogo(
size: 40,
),
),
),
)
SizedBox
This widget allows us to specify the size of the child widget across all screens.
SizedBox(
width: 310.0,
height: 440.0,
child: const Card(child: Text('Hello DarTpoint!')),
)
AspectRatio
This widget allows us to limit the child widget’s size to a certain aspect ratio.
AspectRatio(
aspectRatio: 6/3,
child: Container(
color: Colors.black,
),
),
Baseline
This widget moves the child widget based on the baseline of the child.
child: Baseline(
baseline: 40.0,
baselineType: TextBaseline.alphabetic,
child: Container(
height: 40,
width: 30,
color: Colors.black,
),
)
ConstrainedBox
It’s a widget that lets us impose extra limits on its child widget. It implies that we may force the child widget to
have a constraint without affecting its characteristics.
ConstrainedBox(
constraints: new BoxConstraints(
minHeight: 160.0,
minWidth: 160.0,
maxHeight: 310.0,
maxWidth: 310.0,
),
child: new DecoratedBox(
decoration: new BoxDecoration(color: Colors.blue),
),
),
CustomSingleChildLayout
It is a widget that delegates the layout of a single child to a delegate. The delegate determines the child widget’s
position and the size of the parent widget.
FittedBox
It scales and arranges the child widget based on the fit parameter.
import 'package:flutter/material.dart';
FractionallySizedBox
This widget allows you to size its child widgets based on the fraction of available space.
LimitedBox
We can restrict the size of this widget only when it is unconstrained.
Offstage
It is used to measure the size of a widget without bringing it onto the screen.
OverflowBox
A widget allows us to impose different limitations on its child widget than it receives from its parent. In other
words, it permits the child widget to overflow the parent widget.
Example:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// It is root widget of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Single Layout Widget',
debugShowCheckedModeBanner: false,
theme: ThemeData(
// This is the theme of your application.
primarySwatch: Colors.red,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("OverflowBox Widget"),
),
body: Center(
child: Container(
height: 40.0,
width: 40.0,
color: Colors.white,
child: OverflowBox(
minHeight: 60.0,
minWidth: 60.0,
child: Container(
height: 40.0,
width: 40.0,
color: Colors.yellow,
),
),
),
),
);
}
}
Row
It allows its child widgets to be positioned horizontally.
import 'package:flutter/material.dart';
Column
It allows us to arrange its child widgets vertically.
ListView
It is the most common scrolling widget, allowing us to arrange its child widgets in the scroll direction one after the
other.
GridView
Its child widgets may be arranged as a scrollable, 2D array of widgets. It comprises a repetitive pattern of cells
organized horizontally and vertically.
Expanded
It allows you to make the children of a Row and Column widget take up the most space possible.
Table
A table-based widget that allows us to organize its children.
Flow
It enables us to create a flow-based widget.
Stack
This is a necessary widget mainly used to overlap many child widgets. It enables us to display numerous layers on
the screen.
The following example assists us in comprehending it.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// It is root widget of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Multiple Layout Widget',
debugShowCheckedModeBanner: false,
theme: ThemeData(
// This is theme of our application.
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
alignment: Alignment.center,
color: Colors.green,
child: Stack(
children: <Widget>[
// Max Size
Container(
color: Colors.blue,
),
Container(
color: Colors.yellow,
height: 410.0,
width: 310.0,
),
Container(
color: Colors.black,
height: 230.0,
width: 210.0,
)
],
),
),
);
}
}
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// It is the root widget of our application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo Application', theme: ThemeData(
primarySwatch: Colors.yellow,),
home: HomePage(title: 'Complex layout example'),
);
}
}
class HomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product List")),
body: ListView(
padding: const EdgeInsets.fromLTRB(4.0, 13.0, 2.0, 11.0),
children: <Widget>[
ProductBox(
name: "iPhone11",
description: "iPhone is top branded phone ever",
price: 50000,
image: "iphone11.png"
),
ProductBox(
name: "AndroidS2",
description: "Android is very stylish phone",
price: 12000,
image: "androidS2.png"
),
ProductBox(
name: "Tablet",
description: "Tablet is popular device for official meetings",
price: 26000,
image: "tablet.png"
),
ProductBox(
name: "DellLaptop",
description: "Laptop is most famous electronic device",
price: 38000,
image: "delllaptop.png"
),
ProductBox(
name: "Desktop",
description: "Desktop is most popular for regular use",
price: 13000,
image: "computer.png"
),
],
)
);
}
}
class ProductBoxes extends StatelessWidget {
ProductBoxes({Key key, this.names, this.descriptions, this.prices, this.images}) :
super(key: key);
final String names;
final String descriptions;
final int prices;
final String images;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 120,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image.asset("assets/" + image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
this.names, style: TextStyle(
fontWeight: FontWeight.bold
)
),
Text(this.description), Text(
"Prices: " + this.price.toString()
),
],
)
)
)
]
)
)
);
}
}
In the above code, we construct the widget ProductBox, which holds product details like an image, name, price,
and description. We utilize the following child widgets in the ProductBox widget: Container, Row, Column,
Expanded, Card, Text, Image, and so on.
GESTURES IN FLUTTER
Flutter’s gestures are an exciting feature that allows us to interact with the mobile app (or any touch-based device).
In general, gestures are any physical motion or movement performed by a user to control a mobile device. Here are
some examples of gestures:
When the smartphone screen is locked, we unlock it by swiping our fingers over it.
Tapping a button on our mobile screen and moving an app icon between screens on a touch-based device.
These gestures are used in everyday life to interact with our phone or another touch-based device.
Flutter separates the gesture system into two levels, which are described below:
1. Pointers
2. Gestures
Pointers
The first layer is pointers, which represent primary data regarding user interaction. It provides events that explain
the location and movement of points across the displays such as touches, mice, and style. Flutter does not provide
a means for canceling or stopping the dispatch of pointer events. Flutter has a Listener widget that allows us to
listen to pointer events straight from the widgets layer. The pointer-events are classified into four types:
PointerDownEvents: This allows the pointer to touch the screen at a particular position.
PointerMoveEvents: It allows the pointer to move from one location on the screen to another.
PointerUpEvents: These events enable the pointer to quit contacting the screen.
PointerCancelEvents: This event is sent when pointer interaction is terminated.
Gestures
The second layer represents semantic actions like tap, drag, and scale detected from many individual pointer
events. It can also send out several events related to the gesture lifecycle such as drag start, drag update, and drag
end. The following are some of the most commonly used gestures.
Tap
This involves briefly contacting the screen’s surface with our fingertip and releasing it. The following occurrences
occur as a result of this gesture:
onTapDown
onTapUp
onTap
onTapCancel
Double Tap
It is identical to a Tap gesture, but we must tap twice in a brief period of time. The following occurrences occur as
a result of this gesture:
onDoubleTap
Drag
It allows us to use our fingertips to touch the screen’s surface and move it from one spot to another before
releasing it. Flutter divides drag into two types:
1. Horizontal Drag: With this action, the cursor may move horizontally. It includes the following events:
onHorizontalDragStart
onHorizontalDrag
Update
onHorizontalDragEnd
2. Vertical Drag: This motion enables the cursor to travel vertically. It includes the following events:
onVerticalDragStart
onVerticalDragStart
onVerticalDragStart
Long Press
This refers to touching the screen’s surface in a specific spot for an extended period of time. The following
occurrences occur as a result of this gesture:
onLongPress
Pan
It refers to touching the screen’s surface with a fingertip that can travel in any direction without releasing the
fingertip. The following occurrences occur as a result of this gesture:
onPanStart
onPanUpdate
onPanEnd
Pinch
It refers to zooming into or out of a screen by pinching (moving one’s finger and thumb or bringing them together
on a touchscreen).
Gesture Detector
Using the GestureDetector widget, Flutter provides great support for all forms of motion. The GestureWidget is a
non-visual widget used to detect the user’s gesture. The gesture detector’s basic concept is a stateless widget with
parameters in its constructor for various touch events.
In some cases, there may be multiple gesture detectors at the same position on the screen, and the framework
determines which gesture should be called. The GestureDetector widget determines which gestures to identify
based on which callbacks are not null.
Let’s see how we can utilize these gestures in our app with a simple onTap() event and how the GestureDetector
handles it. This section creates a box widget, design it to our specifications, and then add the onTap() code to it.
Create a new Flutter project and replace the code in the main.dart file with the following:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo Application', theme: ThemeData(
primarySwatch: Colors.blue,),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
MyHomePageState createState() => new HomePageState();
}
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
//It is entry point for your Flutter app.
void main() {
runApp(
MaterialApp(
title: 'Multiple-Gestures Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Multiple-Gestures Demo'),
),
body: DemoApp(),
),
),
);
}
STATE MANAGEMENT
This section goes over state management and how we can handle it in Flutter. We already know that everything in
Flutter is a widget. The widget may be divided into two types: stateless widgets and stateful widgets. There is no
internal state in the Stateless widget. It implies that we can’t edit or modify it once generated until it’s initialized
again. A Stateful widget, on the other hand, is dynamic and has a state. It implies that we can simply modify it
during its lifecycle without reinitializing it.
Application state.
To further grasp the notion of state management, consider the following example. Assume we have a list of
customers or items on our app. Assume we’ve added a new client or product dynamically to that list. The list must
then refresh to see the newly added item in the record. As a result, anytime we add a new item, we must reload the
list. This sort of programming necessitates state management to handle such a circumstance and increase
performance. It’s because the state is updated every time we make a modification or update it.
Flutter’s state management is divided into two conceptual categories, which are listed below:
Ephemeral State
App State
Ephemeral State
Ephemeral state is also called a UI state or local state. It is a sort of state associated with a particular widget, or we
can say that it is a state contained within a single widget. We do not need to utilize state management techniques in
this type of state. Text Field is a frequent example of this condition.
Example:
class Homepage extends StatefulWidget {
@override
HomepageState createState() => HomepageState();
}
In the above example, the _name is an ephemeral state. Only the setState() function within the StatefulWidget’s
class has access to the _name in this case. The build method invokes the setState() function, modifying the state
variables. When this method is called, the widget object is replaced with a new one with the updated variable
value.
App State
It is not the same as the ephemeral state. It is a form of state that we wish to preserve throughout user sessions and
distribute across different portions of our program. As a result, this form of state may be applied globally. It is also
called an application state or shared state at times. User preferences, login information, alerts in a social
networking app, the shopping cart in an e-commerce app, the read/unread status of articles in a news app, and so
on are examples of this state.
The following figure clearly demonstrates the distinction between the ephemeral state and the app state.
ChangeNotifier
A ChangeNotifier is a basic class that notifies its listeners when anything changes. It is simple to comprehend,
implement, and optimize for a small group of listeners. It is utilized for the listener to notice a change model. We
simply use the notifyListener() function to notify the listeners in this case.
Let us develop a model based on ChangeNotifier as an example. The Counter in this model has been enhanced
with a ChangeNotifier, which alerts its listeners when we run notifyListeners (). It is the sole method that a
ChangeNotifier model must implement. We declared two functions in this example, increment and decrement,
used to raise and reduce the value. We may use the notifyListeners() function if the model changes to affect the UI
of our project.
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int _counters;
Counter(this._counters);
getCounter() => _counters;
setCounter(int counters) => _counters = counters;
void increment() {
_counters++;
notifyListeners();
}
void decrement() {
_counters--;
notifyListeners();
}
}
ChangeNotifierProvider
It is a widget that delivers a ChangeNotifier instance to its children. It is part of the provider package. The
following code samples will help us grasp the notion of ChangeNotifierProvider.
In this section, we developed a builder that would produce a new instance of the Counter model.
ChangeNotifierProvider does not rebuild Counter until it is required. When the instance is no longer required, it
will also automatically invoke the dispose() function on the Counter model.
We can use MultiProvider if we need to offer more than one class. The MultiProvider is a list of the providers
utilized inside its scope. We would have to nest our Providers if we didn’t use this, with one being the child of
another and another. We may deduce this from the following code.
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(builder: (context) => Counter()),
Provider(builder: (context) => SomeOtherClass()),
],
child: App(),
),
);
}
Consumer
It is a provider who does not perform anything special. It invokes the provider in a new widget and passes the
build implementation to the builder. The following code describes it in further detail.
return Consumer<Counter>(
builder: (context, counts, child) {
return Text("Total price is: ${counts.total}");
},
);
The consumer widget in the above example requires a constructor, which is invoked whenever the ChangeNotifier
changes. The context, count, and child parameters are sent to the builder function. Every construct() function takes
the first parameter, context. The second parameter is the ChangeNotifier object, and the third argument is the child
utilized for optimization. The consumer widget should be placed as deep in the tree as possible.
FLUTTER IDE
Interactive development environments (IDEs) are software tools that allow users to create and modify text files.
Editors are commonly used in the development profession to refer to source code editors, which have particular
functions for creating and modifying code.
We can build Flutter apps with any text editor that works well with our command-line tools. However, for a
better experience, editor plugins (IDE) are recommended. These plugins include syntax highlighting, code
completion, widget editing assistance, run and debug support, and various other capabilities. Flutter supports a
variety of IDEs for app development. Some of these are covered here, but we can use a different editor.
The most popular IDEs that provide the best support for Flutter application development are:
Android Studio
IntelliJ Idea
Visual Studio
Emac
Codemagic
Android Studio
It is a free, open-source, and rapid tool for developing apps for all types of Android devices. It offers a
comprehensive development experience for Flutter applications, including code completion, navigation, syntax
highlighting, refactoring, widget editing assistance, and run and debug support, among other things. The major
goal of the Android Studio is to speed up development and create high-quality apps for all Android devices. It
enables the developer to resolve specific code errors automatically.
To download the android studio, click here: https://developer.android.com/studio
IntelliJ Idea
JetBrains Company created and maintained IntelliJ IDEA, the most powerful and popular IDE among developers.
It is released under the Apache 2.0 license. It allows you to create apps in a variety of languages. Because it
supports good plugins and has a wide built-in feature set, it will quickly become a preferred IDE for many
developers. When it comes to developing applications in the Dart language, it is the clear winner compared to
other IDEs. It provides a complete app development experience, including smart coding aid for Dart, code
completion, formatting, navigation, intents, refactoring, a built-in debugger, interaction with pub, and the Dart
Analysis Server. It enables us to resolve specific code bugs automatically.
IntelliJ Idea is primarily offered in two editions:
The Community Edition (it is free and open-source).
Edition ULTIMATE (a paid version but a free trial for 30 days).
Click here https://www.jetbrains.com/idea/download/#section=windows to download IntelliJ Idea.
Codemagic
It is also a handy tool for quickly developing, testing, and delivering Flutter applications. Using the Flutter
framework to create an app will speed up the development process. It enables Cinemagic to test and publish the
app. It also aids in marketing our app without causing too many problems. It is a completely free and open-source
IDE. It also allows us to submit anything we want to help enhance its documentation.
Click here https://codemagic.io/start/ to download Codemagic.
FLUTTER SCAFFOLD
In Flutter, the Scaffold widget constructs the fundamental material design visual layout framework. It is fast
enough to build a general-purpose mobile app and offers practically everything we need to create effective and
responsive Flutter apps. This widget can take up the entire screen of the device. In other words, it is primarily
responsible for establishing a foundation for the app screen on which the child widgets may hold and render on the
screen. It includes a plethora of widgets and APIs for displaying Drawer, SnackBar, BottomNavigationBar,
AppBar, FloatingActionButton, and many others.
Scaffold class provides a shortcut for the setting up appearance and feel of program, allowing us to avoid
manually building the individual visual elements. It saves our time from building extra code for the app’s look and
feel.
The Scaffold widget class’s constructor and attributes are as follows:
const Scaffold({
Key key,
this.appBar,
this.body,
this.floatingActionButton,
this.floatingActionButtonLocation,
this.persistentFooterButtons,
this.drawer,
this.endDrawer,
this.bottomNavigationBar,
this.bottomSheet,
this.floatingActionButtonAnimator,
this.backgroundColor,
this.resizeToAvoidBottomPadding = true,
this.primary = true,
})
The title attributes in the above code uses a Text widget to show text on the screen.
2. body: This widget’s other primary and required property, which displays the main content in the Scaffold. It
denotes the area beneath the appBar and behind the floatingActionButton and drawer. By default, the widgets
inside the body are positioned at the top-left of the available space. Look at the following code:
The text “Welcome to DartTpoint” was shown in the body property of the preceding code. Using the
Middle widget, this text is positioned in the center of the page. We’ve also used the TextStyle widget to style
the text, changing the color, font size, and so on.
3. drawer: This is a slider panel located on the body’s side. On mobile devices, it is usually concealed, but the
user may access the drawer menu by swiping left to right or right to left. It shows navigation links in the
application by horizontally sliding the Drawer widget attributes from the Scaffold edge. In an appBar
property, a suitable icon for the drawer is automatically set. The gesture is also programmed to open the
drawer automatically. Look at the following code:
drawer: Drawer(
child: ListView(
children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: Colors.yellow,
),
child: Text(
'Welcome to Dartpoint',
style: TextStyle(
color: Colors.green,
fontSize: 35,
),
), ),
ListTile(
title: Text('1'),
),
ListTile(
title: new Text("Mail Inboxes"),
leading: new Icon(Icons.mail),
),
Divider(
height: 0.2,
),
ListTile(
title: new Text("Prime"),
),
ListTile(
title: new Text("Socials"),
),
ListTile(
title: new Text("Promotion"),
),
],
),
),
We utilize Scaffold’s drawer property in the preceding code to create a drawer. We also used some
additional widgets to make it more appealing. We separated the panel in the ListView widget into two
sections: Header and Menu. The DrawerHeader property changes the panel header, including an icon or
information depending on the application. We used ListTile once more to add the list items to the menu.
4. floatingActionButton: This button appears in the bottom right corner of the screen and floats above the
body. It is a circular icon button that floats over the content of a screen at a designated location to encourage
a key action in the program. The location of the page cannot be modified while scrolling. Scaffold is used to
access the FloatingActionButton widget attributes floatingActionButton. Look at the following code:
We utilized the elevation attribute in the preceding code to create the button a shadow effect. We also utilized
the Icon widget to provide the button an icon using preloaded Flutter SDK icons. When the user presses
button, the onPressed() property is called, and the statements “Floating Action Button” are displayed to the
console.
5. backgroundColor: This parameter is used to provide the background color of the Scaffold widget as a
whole.
backgroundColor: Colors.red,
6. primary: It determines whether or not the Scaffold will be shown at the top of the screen. Its default value is
true, which shows that the appBar’s height is increased by the screen’s status bar height.
7. persistentFooterButton: This is a collection of buttons that appear at the bottom of the Scaffold widget.
These property items are always displayed, even when we browse the Scaffold’s body. It’s always wrapped
by a ButtonBar widget. They appear under the body but above the bottomNavigationBar.
persistentFooterButtons: <Widget>[
RaisedButton(
onPressed: () {},
color: Colors.white,
child: Icon(
Icons.add,
color: Colors.black,
),
), RaisedButton(
onPressed: () {},
color: Colors.blue,
child: Icon(
Icons.clear,
color: Colors.red,
),
),
],
We utilized the RaisedButton that appears at the bottom of the Scaffold in the above code. We may also
use the FlatButton for the RaisedButton.
8. bottomNavigationBar: This property functions similarly to a menu in that it shows a navigation bar at the
bottom of the Scaffold. It may be found in the majority of mobile applications. This attribute enables the
developer to include several icons or words as items in the bar. It should appear beneath the body and
persistentFooterButtons. Look at the following code:
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
fixedColor: Colors.white,
items: [
BottomNavigationBarItem(
title: Text("MyHome"),
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
title: Text("Search"),
icon: Icon(Icons.search),
),
BottomNavigationBarItem(
title: Text("User-Profile"),
icon: Icon(Icons.account_circle),
),
],
onTap: (int itemIndex){
setState(() {
_currentIndex = itemIndex;
});
},
),
To display the menu bar, we utilized the BottomNavigationBar widget in the preceding code. The
fixedColor parameter determines the active icon’s color. The BottomNavigationBarItems widget adds items
to the bar that include text and an icon as child properties. We also used the onTap(int itemIndex) function to
perform an action when we tapped on the items based on their index position.
9. endDrawer: This property is identical to a drawer property, except it is shown on the right side of the screen
by default. It may swipe from right to left or from left to right.
10. resizeToAvoidBottomInset: If true, the body and the Scaffold’s floating widgets should adjust to avoid the
onscreen keyboard. The bottom attribute specifies the height of the onscreen keyboard.
11. floatingActionButtonLocation: It is by default located at the bottom right corner of the screen. It is used to
determine the floatingActionButton’s location. It has a wide range of predefined constants such as
centerDocked, centerFloat, endDocked, endFloat, etc.
FLUTTER CONTAINER
In Flutter, the container is a parent widget that can hold several child widgets and manage them effectively through
width, height, padding, background color, etc. It is a widget that combines the child widgets’ common painting,
positioning, and sizing. It is also a class for storing widgets and positioning them on the screen based on our
requirements. In general, it is similar to a box used to store contents. It provides the user with numerous properties
for customizing its child widgets, such as margin, which divides the container from other contents.
A container widget is equivalent to the HTML <div> element. If this widget does not have any child widgets, it
will automatically occupy the entire screen. Otherwise, it wraps the child widget according to specified height and
width. It should be noted that this widget cannot render directly in the absence of a parent widget. As its parent
widget, we can use Scaffold widget, Center widget, Padding widget, Row widget, or Column widget.
Container({Key key,
AlignmentGeometry alignment,
EdgeInsetsGeometry padding,
Color colors,
double width,
double height,
Decoration decorations,
Decoration foregroundDecoration,
BoxConstraints constraints,
Widget child,
Clip clipBehavior: Clip.none
});
Container(
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
2. color: Color property is used to set background color of the text. It also changes the background color of the
entire container.
Container(
color: Colors.yellow,
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
3. height and width: This property is used to set container’s height and width according to our needs. By
default, container always takes the space based on its child widget.
Container(
width: 210.0,
height: 110.0,
color: Colors.yellow,
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
4. margin: This attribute is used to enclose the container’s empty space. We can notice this by looking at the
white area around the container. Assume we used the EdgeInsets.all(29) function to establish an equal margin
in all four directions, as demonstrated in the following example:
Container(
width: 210.0,
height: 110.0,
color: Colors.yellow,
margin: EdgeInsets.all(22),
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
5. padding: This parameter specifies the space between the container’s border (in all four dimensions) and its
child widget. This may be seen by looking at the gap between the container and the child widget. In this case,
we used EdgeInsets.all(39) to establish the spacing between the text and all four container directions.
Container(
width: 210.0,
height: 110.0,
color: Colors.red,
padding: EdgeInsets.all(39),
margin: EdgeInsets.all(22),
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
6. alignment: This attribute specifies the child’s location within the container. Flutter’s elements may be
aligned in a variety of ways, including center, bottom, bottom center, topLeft, centerRight, left, right, and
many more. We will align its kid to the bottom right position in the next example:
Container(
width: 210.0,
height: 110.0,
color: Colors.red,
padding: EdgeInsets.all(39),
margin: EdgeInsets.all(22),
alignment: Alignment.bottomRight,
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
7. decoration: The developer may use this attribute to add decoration to the widget. It paints or decorates the
widget behind the child. We must utilize the forgroundDecoration option if we wish to decorate or paint in
front of a child. The following image demonstrates the distinction between them, with the
foregroundDecoration covering the kid and the decorative paint behind the child.
Many parameters were supported by the decorating property, including color, gradient, background image,
border, shadow, and so on. Its purpose is to ensure that we may use the color property in either a container or
a decoration, but not both. Look at the following code, where we’ve added a border and shadow property to
adorn the box.
import 'package:flutter/material.dart';
void main() => runApp(App());
/// This Widget is the main application widget.
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Container Example"),
), body: Container(
padding: EdgeInsets.all(39),
margin: EdgeInsets.all(22),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
borderRadius: BorderRadius.circular(9),
boxShadow: [
new BoxShadow(color: Colors.red, offset: new Offset(5.0, 5.0),),
],
),
child: Text("Hello, container widget decoration box",
style: TextStyle(fontSize: 32)),
),
),
);
}
}
8. transform: Developers can rotate the container using the transform attribute. It has the ability to rotate the
container in any direction, hence changing the container coordinates in the parent widget. In the following
example, we will rotate the container along the z-axis.
Container(
width: 210.0,
height: 110.0,
color: Colors.yellow,
padding: EdgeInsets.all(39),
margin: EdgeInsets.all(22),
alignment: Alignment.bottomRight,
transform: Matrix4.rotationZ(0.2),
child: Text("Hello container widget", style: TextStyle(fontSize: 29)),
)
9. constraints: When we want to add extra limitations to the child, we utilize this property. It includes
constructors like tight, loose, expand, and so forth. Let’s look at how we can utilize these constructors in our
app.
tight: If we use the size property in this, it will give fixed value to the child.
Container(
color: Colors.red,
constraints: BoxConstraints.tight(Size size)
: minWidth = size.width, maxWidth = size.width,
minHeight = size.height, maxHeight = size.height;
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
expand: Here, we can choose height, width, or both values to the child.
Container(
color: Colors.yellow,
constraints: BoxConstraints.expand(height: 63.0),
child: Text("Hello, container widget", style: TextStyle(fontSize: 29)),
)
Key points:
The most widely used layout patterns in the Flutter application are row and column widgets.
Both can have several child widgets.
A row or column widget can also be a child widget.
We can extend or constrain a particular children’s widget.
Flutter also allows developers to specify how the child widgets can use in row and column widgets.
Row Widget
This widget distributes its children horizontally on the screen. In other words, it will expect child widgets in the
form of a horizontal array. If the child widgets must occupy the available horizontal area, they must be wrapped in
an Expand widget.
Because it shows the widgets within the viewable view, a row widget does not look scrollable. As a result, it is
regarded wrong to have more children in a row than would fit in the given area. The ListView widget is required to
create a scrollable list of row widgets.
Using the properties of crossAxisAlignment and mainAxisAlignment, we can modify how a row widget aligns
its children based on our preferences. The cross-axis of the row will run vertically, while the main axis will run
horizontally.
The following properties may use to align the row’s children widget:
start: It will start the children at the beginning of the main axis.
end: It will put the children at the very end of the main axis.
center: It will place the children in the center of the main axis.
space between: It will evenly distribute the open space between the children.
spaceAround: It will uniformly distribute the free space between the children, with half of that space placed
before and after the first and final children’s widgets.
space Evenly: It will evenly distribute the free space between the children and before and after the first and
final children’s widgets.
Let’s look at an example where we’re going to align the material such that there’s an even gap around the children
in a row.
import 'package:flutter/material.dart';
void main() { runApp(App()); }
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage()
);
}
}
Column
This widget arranges its children vertically on the screen. In other words, it expects a vertical array of child
widgets. If the child widgets must occupy the available vertical space, they must be wrapped in an Expand widget.
Because it displays the widgets within the viewable view, a column widget does not look scrollable. As a result,
it is considered incorrect if we have more children in a column than would fit in the given area. The ListView
Widget is required to create a scrollable list of column widgets.
Using the properties of mainAxisAlignment and crossAxisAlignment, we can customize how a column widget
aligns its children. The cross-axis of the column will run horizontally, while the main axis will run vertically.
Let’s look at an example where we’re going to align the content such that there’s an even amount of space
between the children in a column.
import 'package:flutter/material.dart';
FLUTTER TEXT
A Text widget in Flutter allows us to show a string of text in our application on a single line. Depending on the
layout limitations, we may split the string across numerous lines or show it entirely on the same line. If no styling
is specified for the text widget, it will use the closest DefaultTextStyle class style. There is no specified style in
this class. In this post, well look at using a Text widget and design it in our application.
Here’s an easy example to help us understand this widget. This example displays the title of our project in the
application bar and a message in the application body.
import 'package:flutter/material.dart';
void main() { runApp(App()); }
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: TextPage()
);
}
}
class TextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Widget Example")
),
body: Center(
child:Text("Welcome to Dartpoint")
),
);
}
}
We utilized a MaterialApp widget to access the home screen via the MyTextPage() class in the preceding code.
This class includes the scaffold widget, which consists of the appBar and body widgets, where we utilized the Text
widget to show the title and body, respectively. It is a simple Text widget scenario in which we must give the string
that we want to display on our page.
The Text widget utilized in our application has the following basic properties:
TextAlign: This property describes how our text should be oriented horizontally. It also has control over the
text’s position.
TextDirection: This property determines how textAlign values influence the layout of our text. Usually, we
write text from left to right, but this argument allows us to modify that.
Overflow: This word indicates when the text will not fit in the available space. It signifies we’ve provided
more text than there for room.
TextScaleFactor: This property is used to scale the text shown by the Text widget. If we set the text scale
factor to 1.5, our text will be 50 percent larger than the chosen font size.
SoftWrap: It is used to determine whether or not to display full-text widget content when there is insufficient
space. If this is correct, it will display all material. Otherwise, it will not display all of the text.
MaxLines: This property specifies the maximum number of lines displayed in the text widget.
TextWidthBasis: It specifies how the text width is defined.
TextHeightBehavior: This property regulates how the paragraph looks between the first and end lines.
Style: This widget’s most famous attribute allows developers to style their text. It supports style by specifying
the foreground and background color, font size, font weight, letter and word spacing, location, shadows, and
so on. See the following table for a better understanding.
Attributes Descriptions
foreground It selects the paint as the text’s foreground.
Background It selects the paint to be used as the text’s background.
fontWeight It determines the text’s thickness.
fontSize It determines the text’s size.
fontFamily It is used to determine the font’s typeface. To do this, we must first download a typeface file for our project and then place it in the
assets/font folder. Finally, configure the pubspec.yaml file so that it can use in the project.
fontStyle It is used to change the font’s style to bold or italic.
Color It is used to determine the text’s color.
letterSpacing It is used to calculate the distance between the text’s characters.
wordSpacing It is used to describe the distance between two text words.
Shadows It is employed to paint behind the text.
Decoration This beautifies text by passing three parameters: decoration, decorationColor, and decorationStyle.
import 'package:flutter/material.dart';
void main() { runApp(App()); }
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.red,
),
home: TextPage()
);
}
}
class TextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Widget Example")
),
body: Center(
child:Text(
"Hello World, Text Widget.",
style: TextStyle(
fontSize: 39,
color: Colors.purple,
fontWeight: FontWeight.w720,
fontStyle: FontStyle.italic,
letterSpacing: 7,
wordSpacing: 22,
backgroundColor: Colors.blue,
shadows: [
Shadow(color: Colors.yellowAccent, offset: Offset(3,1), blurRadius:12)
]
),
)
),
);
}
}
FLUTTER TEXTFIELD
A TextField or TextBox is an input element that stores alphanumeric data such as a name, password, address, etc.
It is a graphical UI control element that allows users to enter text data using programmable code. It can be a single-
line text field (for information that only requires one line) or a multiple-line text field (when more than one line of
information is needed).
TextField is the most often used text input widget in Flutter, allowing users to take keyboard inputs and save
them in an app. The TextField widget may create forms, convey messages, create search experiences, and much
more. Flutter adds underlining to the TextField by default. Using an InputDecoration as the decoration, we can add
numerous properties to TextField such as a label, icon, inline hint text, and error text. If we want to delete the
decorative properties, we must set the decoration to null.
The following code is a TextFiled widget demo in Flutter.
TextField (
decoration: InputDecoration(
border: InputBorder.none,
labelText: 'Enter-name',
hintText: 'Enter-your-name'
),
);
The following are some of the most popular characteristics associated with the TextField widget:
decoration: It is used to display the design around TextField.
border: This property generates a rounded rectangular border around TextField by default.
labelText: It displays the label text on the TextField selection.
hintText: This property displays the hint text within a TextField.
icon: It is used to add icons to the TextField directly.
We’ll go through how to utilize the TextField widget in the Flutter app in the following steps:
Step 1: In the IDE you used, create a Flutter project. We are going to utilize Android Studio in this case.
Step 2: Navigate to the lib folder in Android Studio after opening the project. Open the main.dart file in this
folder and import the material.dart package as shown below:
import 'package:flutter/material.dart';
Step 3: Next, use the void main run app method to call the main MyApp class, and then construct our main
widget class, MyApp extends with StatefulWidget:
Step 4: Next, in the class widget build area, add the Scaffold widget -> Column widget as shown below:
]
)
)
)
);
}
}
Step 5: Finally, create the TextField widget as shown in the following code:
child: TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter-Password',
),
),
BUTTONS IN FLUTTER
Buttons are graphical control elements that allow a user to initiate an event such as performing actions, making
choices, searching for items, and so on. They may be put anywhere in our UI such as dialog, forms, cards, toolbars,
and so on.
Buttons are Flutter widgets, which are included in the material design library. Flutter consists of various buttons
with varying shapes, styles, and functionalities.
The following are the usual features of a button in Flutter:
Themes may easily apply to buttons, shapes, color, animation, and behavior.
We may also customize the icons and text that appear inside the button.
Buttons can be made up of various child widgets to represent various properties.
Flat Button
It is a text label button with little decoration and is presented without elevation. The flat button must have two
properties: kid and onPressed (). It is typically seen in toolbars, dialogues, or in-line with other content. The flat
button has no color by default, and its text is black. However, using the color and textColor properties, we can add
color to the button and text, respectively.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
Raised Button
It is a button with a rectangular body based on the material widget. It seems like a flat button, but it has an
elevation that rises when the button is pressed. It provides depth to the UI along the Z-axis. It contains numerous
attributes such as text color, shape, padding, button color, the color of a disabled button, animation duration,
elevation, etc.
There are two callback functions associated with this button.
onPressed(): This function is called when the button is pressed.
onLongPress(): This function is called when the button is held in place for an extended period.
It should note that if the onPressed() and onLongPressed() callbacks are not given, this button is disabled.
Example:
Replace the following code in the main.dart file.
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
Example:
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(
appBar: AppBar(
title: Text("Button Example"),
backgroundColor: Colors.red,
actions: <Widget>[
IconButton(icon: Icon(Icons.camera_alt), onPressed: () => {}),
IconButton(icon: Icon(Icons.account_circle), onPressed: () => {})
],
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.navigation),
backgroundColor: Colors.yellow,
foregroundColor: Colors.grey,
onPressed: () => {},
),
/*floatingActionButton:FloatingActionButton.extended(
onPressed: () {},
icon: Icon(Icons.save),
label: Text("Save"),
), */
),
);
}
}
Example:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: App(),
));
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class ListItem {
int value;
String name;
ListItem(this.value, this.name);
}
Button Icon
An IconButton is a graphic that has been printed on the Material widget. It is a useful widget that adds a material
design feel to the Flutter UI. We may also change the appearance and feel of this button. Simply put, it is an icon
that responds when the user touches it.
Example:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Button Example"),
),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
double _speakervolume = 0.0;
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(Icons.volume_up),
iconSize: 52,
color: Colors.blue,
tooltip: 'Increase volume by 6',
onPressed: () {
setState(() {
_speakervolume += 6;
});
},
),
Text('SpeakerVolume: $_speakervolume')
],
);
}
}
Inkwell Button
The InkWell button is a material design idea for touch response. This widget is part of the Material widget, where
the ink responses are drawn. It makes the app’s UI more interactive by incorporating gesture feedback. It is mainly
used to create a splash ripple effect.
Example:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
int _volume = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Button Example'),
),
body: Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
splashColor: Colors.yellow,
highlightColor: Colors.green,
child: Icon(Icons.ring_volume, size: 54),
onTap: () {
setState(() {
_volume += 3;
});
},
),
Text (
_volume.toString(),
style: TextStyle(fontSize: 54)
),
],
),
),
),
);
}
}
PopupMenu Button
It is a button that, when pressed, displays the menu and then calls the onSelected method to dismiss the menu. It is
because one of the various possibilities has been chosen. This button has both text and an image. It will mostly use
with the Settings menu to show all available choices. It contributes to a positive user experience.
Example:
import 'package:flutter/material.dart';
void main() { runApp(App());}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
Choice _selectedOption = choices[0];
void _select(Choice choice) {
setState(() {
_selectedOption = choice;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Button Example'),
actions: <Widget>[
PopupMenuButton<Choice>(
onSelected: _select,
itemBuilder: (BuildContext context) {
return choices.skip(0).map((Choice choice) {
return PopupMenuItem<Choice>(
value: choice,
child: Text(choice.name),
);
}).toList();
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(12.0),
child: ChoiceCard(choice: _selectedOption),
),
),
);
}
}
class Choice {
const Choice({this.name, this.icon});
final String name;
final IconData icon;
}
const List<Choice> choices = const <Choice>[
const Choice(name: 'Wi-Fi', icon: Icons.wifi),
const Choice(name: 'Bluetooth', icon: Icons.bluetooth),
const Choice(name: 'Battery', icon: Icons.battery_alert),
const Choice(name: 'Storage', icon: Icons.storage),
];
class ChoiceCard extends StatelessWidget {
const ChoiceCard({Key key, this.choice}) : super(key: key);
final Choice choice;
@override
Widget build(BuildContext context) {
final TextStyle textStyle = Theme.of(context).textTheme.headline;
return Card(
color: Colors.greenAccent,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(choice.icon, size: 120.0, color: textStyle.color),
Text(choice.name, style: textStyle),
],
),
),
);
}
}
Outline Button
It looks similar to the flat button, except it has a thin grey rounded rectangle border around it. The shape property
defines its outline boundary.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Button Example'),
),
body: Center(child: Column(children: <Widget>[
Container(
margin: EdgeInsets.all(28),
child: OutlineButton(
child: Text("Outline Button", style: TextStyle(fontSize: 22.0),),
highlightedBorderColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(17)),
onPressed: () {},
),
),
Container(
margin: EdgeInsets.all(28),
child: FlatButton(
child: Text('Flat Button', style: TextStyle(fontSize: 22.0),),
color: Colors.blueAccent,
textColor: Colors.grey,
onPressed: () {},
),
),
]
))
),
);
}
}
FLUTTER FORMS
Forms are a necessary component of any current mobile and online apps. It is mainly used to interact with the app
and collect information from users. They may execute a variety of functions, depending on the nature of your
business requirements and logic such as user authentication, user addition, searching, filtering, ordering, booking,
and so on. A form may have text fields, buttons, checkboxes, radio buttons, and so on.
Creating a Form
To create a form, use the Form widget provided by Flutter. The form widget serves as a container, allowing us to
group and check the various form fields. When you build a form, you must include the GlobalKey. This key
identifies the form and allows us to validate the form fields.
The form widget uses the child widget TextFormField to allow users to enter text into the text field. This widget
displays a material design text field and validation errors as they occur.
Let’s make a form. Create a Flutter project first, and then change the following code in the main.dart file. We’ve
developed a custom class called MyCustomForm in this code snippet. We define a global key as _formKey within
this class. This key contains a FormState, which may be used to obtain the form widget. We’ve added some custom
styling to this class’s create function, and we’re using the TextFormField widget to give form fields like name,
phone number, date of birth, or simply a regular field. We utilized InputDecoration within the TextFormField to
offer the appearance and feel of your form attributes such as borders, labels, icons, hint, styles, and so on. Finally,
we’ve included a button for submitting the form.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Form Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(appTitle),
),
body: MyCustomForm(),
),
);
}
}
// Create Form widget.
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create the corresponding State class. This class holds data related to form.
class MyCustomFormState extends State<MyCustomForm> {
// Create global key that uniquely identifies the Form widget
// and allows validation of the form.
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
icon: const Icon(Icons.person),
hintText: 'Enter name',
labelText: 'Name',
),
),
TextFormField(
decoration: const InputDecoration(
icon: const Icon(Icons.phone),
hintText: 'Enter phone number',
labelText: 'Phone',
),
),
TextFormField(
decoration: const InputDecoration(
icon: const Icon(Icons.calendar_today),
hintText: 'Enter date of birth',
labelText: 'DOB',
),
),
new Container(
padding: const EdgeInsets.only(left: 160.0, top: 50.0),
child: new RaisedButton(
child: const Text('Submit'),
onPressed: null,
)),
],
),
);
}
}
Validation of a Form
Validation is a method that allows us to fix or confirm a certain standard. It guarantees that the data entered is
legitimate.
Form validation is a standard practice in all digital interactions. To verify a form in Flutter, we must first create
three phases.
Step 1: Create a global key and use the Form widget.
Step 2: Give the input field the validator property by using TextFormField.
Step 3: Make a button to validate form data and display validation errors.
ICONS IN FLUTTER
An icon is a graphic image representing a program or any unique entity that has meaning for the user. It can be
either selectable or non-selectable. The company’s logo, for example, is not selectable. It may also include a
hyperlink that leads to another page. It also serves as a symbol instead of a complete description of the real thing.
Flutter offers an Icon Widget to build icons for our apps. In Flutter, we may create icons using either built-in or
custom icons. Flutter returns a list of all the icons in the Icons class. This tutorial will teach us how to utilize
Flutter icons in your application.
In the following example, we’ll look at a basic icon widget with default settings. Create a new project in the IDE,
then navigate to the lib folder and open the main.dart file. Replace the following code in the main.dart file:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// Widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: IconPage(),
);
}
}
IMAGES IN FLUTTER
In this part, we’ll look at showing images in Flutter. When we build a Flutter app, we include code and assets
(resources). A file that is packed and deployed with the available program at runtime is referred to as an asset.
Static data, configuration files, icons, and images are all examples of assets. Flutter supports many image formats,
including JPEG, WebP, PNG, GIF, animated WebP/GIF, BMP, and WBMP.
The basic principle of most mobile apps is to display photos. Flutter includes an Image widget that lets us show
several images in our mobile application.
assets:
- assets/tablets.png
- assets/bg.png
If the assets folder has many images, we may include them by appending the directory name with a slash
(/).
flutter:
assets:
- assets/
Step 4: Finally, open the main.dart file and insert the following code into it.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('ImageDemo'),
),
body: Center(
child: Column(
children: [
Image.asset('assets/tablets.png'),
Text(
'A tablet is a wireless touch screen computer that is smaller than a notebo
style: TextStyle(fontSize: 22.0),
)
],
),
), ),
);
}
}
Step 5: Run the application. We will see something similar to the image below.
Image.network(
'https://picsum.photos/250?image=9',
)
Imag.Network provides one crucial feature that enables animated gifs. For showing gifs from the Internet, we may
use the following syntax:
Image.network(
'https://github.com/flutter/plugins/raw/master/packages/video_player/doc/demo_ipod.gif?raw=true',
);
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Image Demo'),
),
body: Center(
child: Column(
children: <Widget>[
Image.network(
'https://pixabay.com/photos/pigeons-flock-of-birds-flying-birds-5277317/',
height: 420,
width: 280
),
Text(
'It is an image displays from given url.',
style: TextStyle(fontSize: 22.0),
)
],
),
),
),
);
}
}
FLUTTER LISTS
Lists are the most common components of any web or mobile application. They are composed of many rows of
objects such as text, buttons, toggles, icons, thumbnails, and many others. We may use it to show information such
as menus and tabs or break up the monotony of plain text files.
This section discusses how to interact with Lists in Flutter. Flutter allows us to deal with Lists in a variety of
ways, as detailed below:
Basic Lists
Long Lists
Grid Lists
Horizontal Lists
Basic Lists
Flutter comes with a ListView widget for working with Lists, which is the basic notion of displaying data in
mobile apps. The ListView is an excellent standard for showing lists with only a few elements. ListView also
includes the ListTitle widget, which adds extra visual structure to a list of data.
Example:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Basic List Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(appTitle),
),
body: ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phoneno'),
),
ListTile(
leading: Icon(Icons.contacts),
title: Text('Contactno'),
),
ListTile(
leading: Icon(Icons.settings),
title: Text('Settings'),
),
],
),
),
);
}
}
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp(
products: List<String>.generate(600, (x) => "Product List: $x"),
));
}
class App extends StatelessWidget {
final List<String> products;
App({Key key, @required this.products}) : super(key: key);
@override
Widget build(BuildContext context) {
final appTitle = 'Long-List Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(appTitle),
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${products[index]}'),
);
},
),
),
);
}
}
Example:
import 'package:flutter/material.dart';
void main() {runApp(App());}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = "Grid-List Demo";
return MaterialApp(
title: appTitle,
home: Scaffold(appBar: AppBar(
title: Text(appTitle),
),
body: GridView.count(
crossAxisCount: 3,
children: List.generate(choices.length, (index) {
return Center(
child: SelectCard(choice: choices[index]),
);
}
)
)
)
);
}
}
class Choices {
const Choices({this.title, this.icon});
final String title;
final IconData icon;
}
const List<Choices> choice = const <Choice>[
const Choices(title: 'Home', icon: Icons.home),
const Choices(title: 'Contact', icon: Icons.contacts),
const Choices(title: 'Map', icon: Icons.map),
const Choices(title: 'Phone', icon: Icons.phone),
const Choices(title: 'Camera', icon: Icons.camera_alt),
const Choices(title: 'Setting', icon: Icons.settings),
const Choices(title: 'Album', icon: Icons.photo_album),
const Choices(title: 'WiFi', icon: Icons.wifi),
const Choices(title: 'GPS', icon: Icons.gps_fixed),
];
class SelectCard extends StatelessWidget {
const SelectCard({Key key, this.choice}) : super(key: key);
final Choices choice;
@override
Widget build(BuildContext context) {
final TextStyle textStyle = Theme.of(context).textTheme.display1;
return Card(
color: Colors.lightYellowAccent,
child: Center(child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(child: Icon(choice.icon, size:53.0, color: textStyle.color)),
Text(choice.title, style: textStyle),
]
),
)
);
}
}
Example:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Horizontal Demo List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Container(
margin: EdgeInsets.symmetric(vertical: 25.0),
height: 160.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Container(
width: 160.0,
color: Colors.red,
child: new Stack(
children: <Widget>[
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
),
],
),
),
Container(
width: 149.0,
color: Colors.yellow,
child: new Stack(
children: <Widget>[
ListTile(
leading: Icon(Icons.camera_alt),
title: Text('Camera'),
),
],
),
),
Container(
width: 149.0,
color: Colors.yellow,
child: new Stack(
children: <Widget>[
ListTile(
leading: Icon(Icons.phone),
title: Text('Phoneno'),
),
],
),
),
Container(
width: 149.0,
color: Colors.green,
child: new Stack(
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
],
),
),
Container(
width: 198.0,
color: Colors.grey,
child: new Stack(
children: <Widget>[
ListTile(
leading: Icon(Icons.settings),
title: Text('Setting'),
),
],
),
),
],
),
),
),
);
}
}
pubspec.yaml
dependencies:
flutter:
sdk: Flutter
cupertino_icons: ^0.1.2
fluttertoast: ^3.1.0
It guarantees that you have left two spaces off the left side of a fluttertoast dependency when adding
dependencies. The fluttertoast requirement makes it possible to display toast notifications straightforwardly. It
also allows us to alter the appearance of the toast popup easily.
Step 3: Open the main.dart file and add a toast notification to the widget using the following code provided.
Fluttertoast.showToast(
msg: 'This is a toast notification',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 2,
backgroundColor: Colors.blue,
textColor: Colors.red
);
Let’s look at the whole code for the preceding phases. Replace the following code in the main.dart file. This
code has a button, and when we push it, the toast message is shown by executing FlutterToast. showToast.
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ToastExample extends StatefulWidget {
@override
_ToastExampleState createState() {
return _ToastExampleState();
}
}
CHECKBOX IN FLUTTER
A checkbox is an input component that stores a Boolean value. It is a graphical UI element that lets the user to pick
numerous alternatives from a list of possibilities. A user can simply provide a yes or no answer in this case. A
checked/marked checkbox indicates yes, whereas an unmarked/unchecked checkbox indicates no value.
Checkboxes are often represented as a square box with white space or a tick mark on the screen. The significance
of the checkboxes was described by a label or caption that corresponded to each checkbox.
This section looks at how to use checkboxes in Flutter. There are two sorts of checkboxes in Flutter: a tiny form
of the Checkbox called “checkbox” and the “CheckboxListTile” checkbox, which includes a header and a subtitle.
The following are extensive explanations of these checkboxes:
Checkbox
Attributes Descriptions
Value It is utilized regardless of whether the checkbox is ticked or not.
onChanged When the value is modified, it will be called.
Tristate By default, it is false. It can also have a value of true, false, or null.
activeColor It provided the color of the checkbox that was chosen.
checkColor When they are selected, it specifies the color of the check icon.
materialTapTargetSize It’s used to set the size of the tap target.
Example:
Checkbox(
value: this.showvalue,
onChanged: (bool value) {
setState(() {
this.showvalue = value;
});
},
),
Let’s write the entire code to see how a checkbox appears in Flutter. To begin, create a project in Android Studio,
open the main.dart file, and replace the following code:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp( home: MyHomePage(),));
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool valuefirst = false;
bool valuesecond = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Checkbox Example'),),
body: Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(width: 13,),
Text('Checkbox without Header and Subtitle: ',style: TextStyle(fontSize: 18.0
Checkbox(
checkColor: Colors.yellowAccent,
activeColor: Colors.blue,
value: this.valuefirst,
onChanged: (bool value) {
setState(() {
this.valuefirst = value;
});
},
),
Checkbox(
value: this.valuesecond,
onChanged: (bool value) {
setState(() {
this.valuesecond = value;
});
},
),
],
),
],
)
),
),
);
}
}
groupValue: It specifies the presently chosen item for the radio button group.
title: It is used to set the label for the radio button.
value: It defines the backhand value, represented as a radio button.
onChanged: This function is invoked whenever the user selects a radio button.
ListTile(
title: const Text('www.google.com'),
leading: Radio(
value: BestTutor.dartpoint,
groupValue: _site,
onChanged: (BestTutorSite value) {
setState(() {
_site = value;
});
},
),
),
Let’s look at the whole code for the preceding phases. Replace the following code in the main.dart file.
The Radio widgets are wrapped in ListTiles in this case, and the currently chosen text is provided into
groupValue and kept by the example’s State. The first Radio button will deselect because _site is set to
BestTutorSite.dartpoint. If the second radio button is hit, setState is used to alter the example’s State, changing
_site to BestTutorSite.w3schools. It rebuilds the button with the new groupValue and selects the second button.
import 'package:flutter/material.dart';
void main() => runApp(App());
/// This Widget is the main application widget.
class App extends StatelessWidget {
static const String _title = 'Radio-Button-Example';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
enum BestTutorSite { dartpoint, w3school, tutorialpoint }
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
BestTutorSite _site = BestTutorSite.dartpoint;
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: const Text('www.dartpoint.com'),
leading: Radio(
value: BestTutorSite.dartpoint,
groupValue: _site,
onChanged: (BestTutorSite value) {
setState(() {
_site = value;
});
},
),
),
ListTile(
title: const Text('www.w3school.com'),
leading: Radio(
value: BestTutorSite.w3school,
groupValue: _site,
onChanged: (BestTutorSite value) {
setState(() {
_site = value;
});
},
),
),
ListTile(
title: const Text('www.tutorialpoint.com'),
leading: Radio(
value: BestTutorSite.tutorialpoint,
groupValue: _site,
onChanged: (BestTutorSite value) {
setState(() {
_site = value;
});
},
),
),
],
);
}
}
LinearProgressIndicator
The linear progress bar displays the task’s progress in a horizontal line.
Flutter primarily provides two sorts of linear progress indicators:
1. Determinate: The Determinate progress bar shows the real amount of progress made at each assignment
stage. Its value will rise monotonically from 0.0 to 1.0 to reflect the quantity of work accomplished at the
moment. To create a deterministic progress indicator, we must utilize a non-null number ranging from 0.0 to
1.0.
2. Indeterminate: An indeterminate progress bar does not reflect how far you are along in finishing the
activity. It suggests we don’t know when the work will complete. It makes progress without expressing how
far it has come. Using a null value, we may create an indeterminate progress indication.
The following are the most prevalent characteristics of a linear progress indicator:
double value: It is used to indicate a non-null number between 0.0 and 1.0, representing the completion of
task progress.
Color BackgroundColor: This property is used to specify the color of the widget’s background.
<Color> value for animation
Color: As an animated value, it is used to determine the color of the progress indication.
Example: The code demonstrates the usage of an indeterminate linear progress bar to display a download
where we do not know when it will complete. A floating button is utilized to change the status from not
downloading to downloading. It displays a text when there is no downloading; otherwise, it displays the
progress indicator.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LinearProgressIndicatorApp(),
);
}
}
class LinearProgressIndicatorApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return LinearProgressIndicatorAppState();
}
}
class LinearProgressIndicatorAppState extends State<LinearProgressIndicatorApp> {
bool _loading;
@override
void initState() {
super.initState();
_loading = false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Linear Progress Bar"),
),
body: Center(
child: Container(
padding: EdgeInsets.all(14.0),
child: _loading? LinearProgressIndicator() : Text(
"Press button for downloading",
style: TextStyle(fontSize: 29)),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_loading = !_loading;
});
},
tooltip: 'Download',
child: Icon(Icons.cloud_download),
),
);
}
}
Sometimes we want to create a fixed progress bar that shows how long it will take to complete the task. In
such instance, we can simulate a download that will take some time to complete the task and update the
LinearProgressIndicator value as follows:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LinearProgressIndicatorApp(),
);
}
}
class LinearProgressIndicatorApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return LinearProgressIndicatorAppState();
}
}
class LinearProgressIndicatorAppState extends State<LinearProgressIndicatorApp> {
bool _loading;
double _progressValue;
@override
void initState() {
super.initState();
_loading = false;
_progressValue = 0.1;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Linear Progress Bar"),
),
body: Center(
child: Container(
padding: EdgeInsets.all(14.0),
child: _loading
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
LinearProgressIndicator(
backgroundColor: Colors.cyanAccent,
valueColor: new AlwaysStoppedAnimation<Color>(Colors.blue),
value: _progressValue,
),
Text('${(_progressValue * 100).round()}%'),
],
)
: Text("Press button for downloading", style: TextStyle(fontSize: 28)),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_loading = !_loading;
_updateProgress();
});
},
tooltip: 'Download',
child: Icon(Icons.cloud_download),
),
);
}
// this function updates progress value
void _updateProgress() {
const oneSec = const Duration(seconds: 3);
new Timer.periodic(oneSec, (Timer t) {
setState(() {
_progressValue += 0.1;
// we "finish" downloading here
if (_progressValue.toStringAsFixed(1) == '1.0') {
_loading = false;
t.cancel();
return;
}
});
});
}
}
CircularProgressIndicator
It is a spinning widget that indicates the waiting process in your application. It depicts the progress of a task in the
form of a circle. It also shows the progress bar in two modes: determined and indeterminate.
We utilize a fixed progress bar when we wish to represent the status of ongoing tasks such as the percentage of
downloading or uploading files. We may display the progress by entering a number between 0.0 and 1.0.
We utilize an indefinite progress bar when we don’t want to know the proportion of a running process.
CircularProgressIndicator displays an indefinite progress indicator by default.
In the following example, we will see the circular progress indicator in an indeterminate mode, which does not
reflect the progress of any work. It repeatedly displays the circles, indicating that something is being worked out
and that we must wait for its completion. There is no need to specify any value to the CircularProgressIndicator()
constructor for this. Look at the following code:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Progress Bar Example'),
),
body: Center(
child: CircularProgressIndicatorApp()
),
),
);
}
}
FLUTTER SLIDER
In Flutter, a slider is a material design widget used to choose a range of values. An input widget allows us to
specify a range of values by dragging or pushing on the desired position. In this post, we will demonstrate how to
utilize the slider widget in Flutter to configure the range of values and how to alter the style of a slider.
We usually utilize the slider widget to change a value. As a result, the value must be stored in a variable. The
slider class in this widget requires the onChanged() method. This function will be called anytime when the slider
position is changed.
A slider can choose a value from a set of continuous or discrete values. It employs a continuous range of
numbers by default. If we wish to use discrete values, we must supply a non-null value for divisions. This discrete
division shows the number of discrete intervals. Before acquiring the value, we must first specify the minimum
and maximum values. The slider has min and max parameters for set the minimum and maximum limits. For
example, if we had a range of values ranging from 0.0 to 50.0 with divisions of 10, the slider would accept values
such as 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
Properties of Slider
There are just two mandatory arguments, and the others are optional.
Attributes Type Descriptions
Value double It is a mandatory input that specifies the current value of the slider.
onChanged double It is a necessary parameter that is called when the user drags the slider to a new value. The slider is disabled if it is
null.
onChangedStart double It is an optional parameter called when we begin to choose a new value.
onChangedStart double A non-mandatory parameter is called whenever we have finished picking a new value for the slider.
Max double It is an optional input that specifies the maximum value the user may use. It is set to 1.0 by default. It must be more
than or equal to the minimum.
Min double It is an optional input that specifies the smallest value that the user can use. It is set to 0.0 by default. It must be less
than or equal to the maximum.
Divisions int It is responsible for determining the number of discrete divisions. If it is not present, the slider is continuous.
Label string It defines the text label that will appear above the slider. It shows the position of a separate slider.
activeColor class It determines the color of the slider track’s active area.
Color
inactiveColor class It determines the color of the slider track’s inactive part.
Color
SemanticFormatterCallback A callback is used to generate a semantic value. It is set to a percentage by default.
Slider(
min: 0,
max: 99,
value: _value,
onChanged: (value) {
setState(() {
_value = value;
});
},
),
With the aid of an example, let us understand how to utilize the slider in Flutter. The value was saved as an integer
in the following code, which had to be converted to double when passed as a value parameter and then rounded to
integer inside the onChanged function. We’ve also made the active section of the slider blue and the inactive
portion orange.
import 'package:flutter/material.dart';
void main() => runApp(App());
// This Widget is main application widget.
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MySliderApp(),
);
}
}
class MySliderApp extends StatefulWidget {
MySliderApp({Key key}) : super(key: key);
@override
_MySliderAppState createState() => _MySliderAppState();
}
class _MySliderAppState extends State<MySliderApp> {
int _value =7;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Slider Demo'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
Icon(
Icons.volume_up,
size: 44,
),
new Expanded(
child: Slider(
value: _value.toDouble(),
min: 1.0,
max: 22.0,
divisions: 10,
activeColor: Colors.blue,
inactiveColor: Colors.yellow,
label: 'Set volume value',
onChanged: (double newValue) {
setState(() {
_value = newValue.round();
});
},
semanticFormatterCallback: (double newValue) {
return '${newValue.round()} dollars';
}
)
),
]
)
),
)
);
}
}
FLUTTER SWITCH
A switch is a two-state UI element that allows you to toggle between the ON (Checked) and OFF (Unchecked)
states. Typically, a button with a thumb slider allows the user to move back and forth to select an ON or OFF
choice. It works in the same way as a house’s electrical switches.
In Flutter, a switch is a widget that allows you to choose between two options: ON or OFF. It does not keep the
condition alive. It will use the onChanged property to keep the states updated. If the value returned by this property
is true, the switch is ON; otherwise, it is false. When this attribute is set to null, the switch widget is turned off.
This post will learn how to use a switch widget in a Flutter application.
Example: We have defined a switch widget in this application. When we toggle the switch widget, the onChanged
property is called with the switch’s new state as the value. As shown in the following code, we have defined a
Boolean variable is Switched to hold the switch status.
Create a Flutter application in the IDE you’re using. Then, in the lib folder, replace main.dart with the following
code:
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red
title: Text("Switch Example"),
),
body: Center(
child: SwitchScreen()
),
)
);
}
}
class SwitchScreen extends StatefulWidget {
@override
SwitchClass createState() => new SwitchClass();
}
class SwitchClass extends State {
bool isSwitched = false;
var textValue = 'Switch is OFF';
void toggleSwitch(bool value) {
if(isSwitched == false)
{
setState(() {
isSwitched = true;
textValue = 'Switch Button ON';
});
print('Switch Button ON');
}
else
{
setState(() {
isSwitched = false;
textValue = 'Switch Button OFF';
});
print('Switch Button OFF');
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.left,
children:[ Transform.scale(
scale: 2,
child: Switch(
onChanged: toggleSwitch,
value: isSwitched,
activeColor: Colors.blue,
activeTrackColor: Colors.green,
inactiveThumbColor: Colors.redAccent,
inactiveTrackColor: Colors.yellow,
)
),
Text('$textValue', style: TextStyle(fontSize: 22),)
]);
}
}
CHARTS IN FLUTTER
A chart is a graphical depiction of data that uses symbols such as a line, bar, pie, and so on to represent the data.
The chart operates just like a standard chart in Flutter. In Flutter, we use a chart to convey the data in a graphical
format that helps the user to grasp it quickly. We may also draw a graph to show the rise and fall of our values. The
graphic makes it simple to understand the data and allows us to see the results monthly or yearly whenever we
need it.
Line Chart
It is a graph that connects individual data points with lines. It displays the information as a sequence of data points.
It is mainly used to track changes across short and extended periods.
Example:
LineChart(
LineChartData(
// write logic
),
);
Bar Chart
It is a graph that uses rectangular bars to represent categorical data. It can be both horizontal and vertical.
Example:
BarChart(
BarChartData(
// write logic
),
);
Example:
PieChart(
PieChartData(
// write logic
),
);
dependencies:
flutter:
sdk: Flutter
fl_chart: ^0.10.1
After we’ve added the dependency, click the get packages link in the top left corner of the screen. Now, open the
main.dart file and replace the following code:
import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
void main() => runApp(App());
/// This Widget is main application widget.
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
FLUTTER TABLE
A table enables the user to organize data into rows and columns. It is used to store and present our data in an
organized fashion, allowing us to compare pairs of related variables readily.
Flutter also lets the user design a table layout in the mobile application. In Flutter, we may make a table by
utilizing the Table widget, which employs the table layout method for its children. This widget contains numerous
settings to improve or adjust the table arrangement. These are the properties: border, children, columnWidths,
textDirection, textBaseline, etc.
TableRow(children: [
TableCell(child: Text('dartpoint')),
TableCell(
child: Text('Flutter App'),
),
TableCell(child: Text('Android App')),
TableCell(child: Text('My-SQL')),
]),
import 'package:flutter/material.dart';
void main() {runApp(App());}
class App extends StatefulWidget {
@override
_TableExample createState() => _TableExample();
}
class _TableExample extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Table Example'),
),
body: Center(
child: Column(children: <Widget>[
Container(
margin: EdgeInsets.all(22),
child: Table(
defaultColumnWidth: FixedColumnWidth(130.0),
border: TableBorder.all(
color: Colors.yellow,
style: BorderStyle.solid,
width: 3),
children: [
TableRow( children: [
Column(children:[Text('Website', style: TextStyle(fontSize: 21.0))]),
Column(children:[Text('Tutorial', style: TextStyle(fontSize: 21.0))]),
Column(children:[Text('Review', style: TextStyle(fontSize: 21.0))]),
]),
TableRow( children: [
Column(children:[Text('Javapoint')]),
Column(children:[Text('Flutter')]),
Column(children:[Text('5*')]),
]),
TableRow( children: [
Column(children:[Text('Dartpoint')]),
Column(children:[Text('My-SQL')]),
Column(children:[Text('5*')]),
]),
TableRow( children: [
Column(children:[Text('Dartpoint')]),
Column(children:[Text('Flutter')]),
Column(children:[Text('5*')]),
]),
],
),
),
])
)),
);
}
}
FLUTTER CALENDAR
It is a system for organizing days, weeks, or months for business, religious, social, or administrative purposes. It
maintains track of which events occur on which dates and when the special events occur. This part goes through
how to show and use the calendar widget in our Flutter app.
Flutter provides a simple widget called table calendar to display the calendar in our app. The table calendar is
very customizable and has many features like gesture, animation, and numerous formats.
The table calendar has several characteristics, which are listed below:
API is simple to use.
Custom Builders are available for UI control.
Vertical auto-sizing is available.
It has lovely animations.
It is capable of handling gestures.
It supports various calendar formats, including month, week, year, and so on.
We can also utilize several weekday forms.
Let’s go over how to make and show a calendar step by step.
Step 1: In the IDE you’re using, create a new Flutter project and name it Flutter Calendar Example.
Step 2: Run the project, browse the lib folder, and double-click the pubspec.yaml file. The table calendar
dependent must be added to this file as follows:
dependencies:
flutter:
sdk: Flutter
table_calendar: ^2.1.0
Step 3: After adding the dependency above, we must execute the following command to obtain the necessary
packages:
import 'package:syncfusion_flutter_calendar/calendar.dart';
Step 5: Next, we need to create a calendar controller and set the calendar to CalendarController.
CalendarController _controller;
@override
void initState() {
super.initState();
_controller = CalendarController();
}
Step 6: The calendar widget must now be added as a child of any widget. Here, we’ll make the calendar
widget a child of the scaffold widget.
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
TableCalendar()
],
),
),
)
Step 7: We can now write our logic and style the calendar to display it.
Example:
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: HomeCalendarPage(),
);
}
}
class HomeCalendarPage extends StatefulWidget {
@override
_HomeCalendarPageState createState() => _HomeCalendarPageState();
}
class _HomeCalendarPageState extends State<HomeCalendarPage> {
CalendarController _controller;
@override
void initState() {
super.initState();
_controller = CalendarController();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Calendar Example'),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TableCalendar(
initialCalendarFormat: CalendarFormat.month,
calendarStyle: CalendarStyle(
todayColor: Colors.green,
selectedColor: Theme.of(context).primaryColor,
todayStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 23.0,
color: Colors.grey)
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonDecoration: BoxDecoration(
color: Colors.brown,
borderRadius: BorderRadius.circular(23.0),
),
formatButtonTextStyle: TextStyle(color: Colors.red),
formatButtonShowsNext: false,
),
startingDayOfWeek: StartingDayOfWeek.monday,
onDaySelected: (date, events) {
print(date.toUtc());
},
builders: CalendarBuilders(
selectedDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(6.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(9.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.black),
)),
todayDayBuilder: (context, date, events) => Container(
margin: const EdgeInsets.all(6.0),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(9.0)),
child: Text(
date.day.toString(),
style: TextStyle(color: Colors.yellow),
)),
),
calendarController: _controller,
)
],
),
),
);
}
}
CHAPTER SUMMARY
This chapter covered Flutter widgets, where we discussed layouts, gestures, state management, and Flutter IDE.
Moreover, we covered icons, buttons, calendar, lists, checkboxes, and tables.
Appraisal
DOI: 10.1201/9781003299363-6
FLUTTER PACKAGES
A package is a namespace that holds a collection of classes, interfaces, and
sub-packages that are all of the same kind. Packages are analogous to
different directories on our computers, where we could have videos in one
folder, photographs in another, software in another, and so on. Dart
organizes and distributes a bundle of functionality in Flutter via a package.
Flutter always supports shared packages provided to the Flutter and Dart
ecosystem by other developers. The packages enable us to construct the app
without starting from scratch.
The following is the general structure of the package (assume a demo
package as mycustom package):
lib/src/*: This directory includes private Dart code files.
lib/mydemo package.dart: It is the primary Dart code file.
FLUTTER SLIVERS
Sliver is a scrollable area section used to create a custom scrolling effect.
Put another way; the sliver widget is a slice of the viewport. We can use
slivers to implement all scrollable views such as ListView and GridView. It
is a lower-level interface that gives you complete freedom to construct a
scrollable area. It comes in handy when scrolling through a significant
number of child widgets in a scrollable area. Because they are dependent on
the viewport, they can alter shape, size, and extent based on various events
and offsets.
Flutter offers a variety of slivers, some of which are listed below:
SliverAppBar
SliverList
SliverGrid
SQLite Database
SQLite is a well-known database software library that offers a relational
database management system for local and client storage. It is a lightweight
and tried-and-true database engine with characteristics such as self-
contained, server-less, zero-configuration, transactional SQL database
engine.
The Flutter SDK does not natively support SQLite. Instead, it includes
the sqflite plugin, which handles all database operations in a manner
comparable to the SQLite library.
TESTING IN FLUTTER
Testing is a process used to ensure that a program or application is bug-free
and fits the user’s needs. It assures that the actual outcome is consistent
with the predicted result. It also aids in enhancing software or applications
in terms of efficiency, usability, and correctness.
Testing is a critical part of the application development life cycle for
ensuring the application’s quality. It is the most time-consuming stage of
the application or software development process.
The Flutter framework is a wonderful tool for automating application
testing. To thoroughly test an application, automated testing is divided into
three forms. These are their names:
Unit Testing
Widget Testing
Integration Testing
Dart only became popular among developers once the Flutter project gained
traction. Even if Dart was a fantastic language with great productivity tools
and documentation from its inception, who cares about the language when
large corporations aren’t utilized in production? But now we’ve gotten to
the stage where, after learning Dart, we can perform valuable things with it.
Companies are now utilizing Flutter, and developers use Dart by default in
production. Furthermore, a sizable developer community is willing to share
their expertise, experiences, and Dart learning process. We feel now is a
wonderful moment to begin studying Dart if we haven’t already.
When you spend so much time learning a new technology, you want to
be especially cautious about its past, present, and future. After months of
learning something new, the last thing you want is for that technology to
become outdated, deprecated, or fall out of industry standards.
You can be concerned about everything else regarding the Dart language,
but you should never be concerned about the language’s development and
preservation. Dart is one of Google’s fastest-growing languages, and it is
utilized by several of its products, including Adwords, Flutter, Fuchsia,
AngularDart, and others. Outside of Google, this language is used in
Alibaba, Adobe, MailChimp, and JetBrains production.
Dart may be compiled by AOT or JIT. Flutter uses this reality because
JIT compilation speeds up development (through Hot Reloading and other
such features), but AOT compilation provides superior optimization during
release time. Hot Reloading is enabled by default in Flutter, which helps
developers be more productive.
A
Abstract classes in Dart, 148
declaring, 149
rules for, 148–149
usage, 149–150
Actual parameter, 104
add() function, 56–58, 64
addAll() function, 58, 72
Advantages, of Flutter, 3–4
Align, 215
Android Studio, 237, 324
Anonymous function in Dart, 107
lexical closure, 109–110
lexical scope, 108–109
appBar, 239
App state, 233
ChangeNotifier, 234
ChangeNotifierProvider, 235
Consumer, 236
Architecture of Flutter framework, 203
Flutter Engine, 203
Foundation Library, 203
specific widgets design, 203
gestures, 204
layers, 204
state management, 204
widgets, 203
Arithmetic operators in Dart, 39
AspectRatio, 215
Assignment operator, 40–41
Async* keyword, 179
Asynchronous generators, 177–178
Async in Dart, 184
concurrency, 187
achieving, 188
Dart async and await, 186–187
Dart await keyword, 187
Dart Future, 186
Dart unit testing, 190–191
grouping test cases, 193
group of test cases, 191–192
synchronous and asynchronous, difference between, 185–186
unit testing, 188–189
advantages of, 190
task, 189
Await keyword, 187
B
backgroundColor, 242, 288, 297
Bar chart, 309
Baseline, 215–216
Bitwise operators, 43–44
Block in Dart, 28
body (widget), 239–240
Boolean in Dart, 99–100
bottomNavigationBar, 243–244
Breakpoints, 164
creation, in WebStorm, 164
Built-in identifiers, 32
Button icon, 268–269
Buttons in Flutter, 260
button icon, 268–269
drop-down button, 266–268
flat button, 261–262
floating activity button (FAB), 264–265
InkWell button, 269–270
outline button, 272–274
popupmenu button, 270–272
raised button, 263–264
C
Calendar, 316–321
Call() function, 179–180
Cascade notation Operators, 45
Center, 214
ChangeNotifier, 234
ChangeNotifierProvider, 235
Characteristics of Dart, 11
browser support, 14
community, 14
concurrency, 13
easy to learn, 13
extensive libraries, 13
flexible compilation, 13
object-oriented, 12–13
objects, 14
open source, 12
platform independent, 12
type safe, 13
Charts in Flutter, 309
bar chart, 309
line chart, 309
pie or donut chart, 310–314
Checkbox in Flutter, 291–293
Checked mode, 29
Child class, 133
CircularProgressIndicator, 301–302
Codemagic, 238
CodeUnitAt() function, 54, 78–79
Collection in Dart, 165
collections iteration, 166
HashMap class, 167
Collections iteration, 166
Column, 252–254
Command-line options for Dart, 29
Comments in Dart, 30
documentation comments, 31
multi-line comments, 31
single-line comments, 30
compareTo(), 54
Comparison operators, see Relational operator
Complex layout, building, 222–225
Concurrency, 187
achieving, 188
Conditional Operators, 44–45
ConstrainedBox, 216
Constructor, 119
creating, 120–121
types of, 121
default constructor/no-argument constructor, 121
named constructors, 122
parameterized constructor, 122
Consumer, 236
Container, 214, 244
requirement in Flutter, 244–245
Container class constructors, 245
Container widget properties, 245
alignment, 247
child, 245
color property, 245
constraints, 248–249
decoration, 247–248
height and width, 246
margin, 246
padding, 246
transform, 248
contains() function, 66
Contextual keywords, 32
Control flow statement, 82
Dart decision-making statements, 83
Custom exceptions, 160
Custom libraries, creating, 173
as an example, 174–175
library connecting, 174
library declaration, 174
CustomScrollView, 328
CustomSingleChildLayout, 216
D
Dart, 323–325
abstract classes in, 148
declaring, 149
rules for, 148–149
usage, 149–150
anonymous function in, 107
lexical closure, 109–110
lexical scope, 108–109
collection in, 165
collections iteration, 166
HashMap class, 167
comments in, 30
documentation comments, 31
multi-line comments, 31
single-line comments, 30
features of, 12
function in, 101
with an argument and a return value, 105
calling a function, 103
function benefits, 102
function defining, 102–103
with no parameter and return value, 105–106
with no parameter and without a return value, 106–107
with parameter and without a return value, 107
passing arguments to the function, 103–104
return a value from the function, 104
inheritance in, 132
hierarchical inheritance, 136–137
multilevel inheritance, 135–136
single level inheritance, 134–135
keywords in, 31–32
method overriding in, 141
benefit of, 146
example of, 143–145
polymorphism, 142–143
rules of, 146
using super keyword, 145–146
methods in, 139
class methods, 140–141
instance methods, 140
object-oriented concepts in, 113
abstract class, 115
class, 114
inheritance, 114
interfaces, 115
object, 114
polymorphism, 115
operator types, 38
arithmetic operators in Dart, 39
assignment operator, 40–41
Bitwise operators, 43–44
Cascade notation Operators, 45
Conditional Operators, 44–45
Logical Operators, 43
relational operator, 41–42
Type Test Operators, 42–43
unary operators (post and pre), 39–40
packages in, 169
package manager in Dart, 170–171
read XML string, 171–172
return value in, 110–111
runes in, 78
String.codeUnitAt() method, 78–79
String.codeUnits property, 79
String.runes property, 79
sets in, 63
access the set element, 65–66
add element into set, 64–65
dart finding element in set, 66
initializing set, 63
super constructor in, 137
explicit super, 139
implicit super, 138
symbol in, 74–77
this keyword in, 123
class variable, 125
class variable and instance variable, difference between, 126
instance variable, 125
local variables, 125
variable in, 35
Dart variable declaration, 36
declaring the variable as having multiple values, 36–37
default value, 37
final and const, 37
type annotations, 36
variable creation rule, 35
Dart, installation of, 20
basic Dart syntax, 26
Dart identifiers, 27
string interpolation and Dart printing, 28
block in Dart, 28
command-line options for Dart, 29
enable checked mode, 29
checked mode, 29
production mode, 29–30
first program in Dart, 25
running on browser, 26
using command line, 26
using IDE, 26
line breaks and Dart whitespace, 28
on Linux, 23
apt-get, installation using, 23–24
dart2js, tool of, 25
Debian package, installation of, 24
installation of Dark SDK on Mac, 24
online Dart, editor of, 24–25
support of Dart IED, 25
semicolon, 28
on Windows, 21–23
Dart, number in, 49
Dart double, 49–50
Dart integer, 49
Parse() method in Dart, 50
number methods, 51
number properties, 51
Dart Async, 184, 186–187
concurrency, 187
achieving, 188
Dart async and await, 186–187
Dart await keyword, 187
Dart Future, 186
Dart unit testing, 190–191
grouping test cases, 193
group of test cases, 191–192
synchronous and asynchronous, difference between, 185–186
unit testing, 188–189
advantages of, 190
task, 189
Dart await keyword, 187
Dart Boolean data type, 34, 99–100
Dart callable classes, 179–181
Dart classes and object, 115
advantages of objects, 119
assessing instance variable and function, 118–119
creating class objects in Dart, 117–118
defining a class in Dart, 116
object in Dart, 117
Dart concurrency, 187–188
Dart Constants, 47
define constants using const keyword, 48–49
using final keyword, define constant, 48
Dart decision-making statements, 83
Dart dynamic type, 35
Dart exceptions, 155
custom exceptions, 160
finally block, 158–159
throwing an exception, 159
try/on/catch blocks, 156–158
Dart Future, 186
Dart Generator, 176
async* keyword, 179
asynchronous generators, 177–178
sync* keyword, 178
synchronous generator, 176–177
yield keyword, 178
Dart generics, 167
generic map, 169
Dart html DOM, 193
event handling, 196–197
finding DOM elements, 194–195
Dart identifiers, 27
Dart interfaces, 150
declaring an interface, 150
implementing an interface, 151
implementing interfaces, rules for, 153
implementing multiple inheritance, 151–153
Dart isolates, 181
create and start an isolate, 181–183
stop an isolate, 183
complete program, 183–184
Dart iterating list elements, 63
Dart iterating over a set element, 67
Dart lists, 34
Dart Loop, 94
do-while Loop, 98–99
for in Loop, 96
for Loop in Dart, 94–95
infinite while loop, 97
logical operator while loop, 98
nested for loop, 95–96
selection of the Loop, 99
while loop, 97
Dart Map, 34, 69
declaring, 70
using map constructor, 70–71
using map literals, 70
map methods, 72–74
map properties, 71–72
Dart Metadata, 164–165
Dart Number, 33
Dart programming, 9, 10–11
characteristics of Dart, 11
browser support, 14
community, 14
concurrency, 13
easy to learn, 13
extensive libraries, 13
flexible compilation, 13
object-oriented, 12–13
objects, 14
open source, 12
platform independent, 12
type safe, 13
default value, 20
fundamental Darts program, 17–18
key actions, 18–19
libraries of Dart, 14
Dart web, 16
native Dart, 16
platforms, 15–16
runtime of Dart, 16–17
variables, 19–20
Dart Recursion, 111
base condition in, 112
recursive function in Dart, 112
recursive function qualities, 112–113
working of, 112
Dart remove all set element, 68
Dart Runes, 34
Dart Set, 63
access the set element, 65–66
add element into set, 64–65
dart finding element in set, 66
initializing set, 63
operations, 68–69
properties, 69
Dart String, 51, 78
printing string, 52
string concatenation, 52
string interpolation, 53
string methods, 54
methods and descriptions, 54
string properties, 53
Dart symbols, 35
Dart unit testing, 190–191
Database concepts in Flutter, 329
Data string, 33
Data types and control flow statement, 47
Boolean in Dart, 99–100
control flow statement in Dart, 82
flow statement categories, 82–83
Dart Constants, 47
define constants using const keyword, 48–49
using final keyword, define constant, 48
Dart Map, 69
declaring, 70–71
map methods, 72–74
map properties, 71–72
enumeration in Dart, 80
enumeration initialization, 80–81
if else-if statement, 87
nested if-else statement, 89–91
if-else statement, 85–87
if statements, 84–85
lists in Dart, 54
Add() method, 57–58
AddAll() method, 58
Dart iterating list elements, 63
Growable list, 56–57
Insert() method, 58–59
InsertAll() method, 59
list properties, 57–58
lists types, 55–56
Remove() Method, 61
RemoveAt() Method, 61–62
RemoveLast() Method, 62
RemoveRange() Method, 62–63
replaceRange(), 60
updating list, 59–60
loops in Dart, 94
do-while Loop, 98–99
for in Loop, 96
For Loop in Dart, 94–95
infinite while loop, 97
logical operator while loop, 98
nested for loop, 95–96
selection of the Loop, 99
while loop, 97
number in Dart, 49
Dart double, 49–50
Dart integer, 49
Parse() method in Dart, 50–51
runes in Dart, 78
String.codeUnitAt() method, 78–79
String.codeUnits property, 79
String.runes property, 79
set element, removing, 67
Dart iterating over a set element, 67
Dart remove all set element, 68
Dart Set operations, 68–69
Dart Set properties, 69
TypeCast set to list, 68
sets in Dart, 63
access the set element, 65–66
add element into set, 64–65
dart finding element in set, 66
initializing set, 63
string, printing, 52
string concatenation, 52
string interpolation, 53
string methods, 54
string properties, 53
switch case statement, 91
benefits of, 94
symbol in Dart, 74
Dart convert symbol to string, 77
Data types in Dart, 32
Dart Boolean, 34
Dart dynamic type, 35
Dart lists, 34
Dart maps, 34
Dart Number, 33
Dart Runes, 34
Dart symbols, 35
Data string, 33
Debugging in Dart, 164
Default constructor, 121
Determinate progress bar, 296–297
Documentation comments, 31
DOM elements, finding, 194–195
Donut chart, 310–314
Double value, 33
Do-while Loop, 98–99
Drag, 227
drawer (widget), 240–241
Drop-down button, 266–268
E
elementAt() function, 65
Emacs, 238
endDrawer, 244
Enumeration in Dart, 80
enumeration initialization, 80–81
Ephemeral state, 232–233
Explicit super, 139
F
FAB, see Floating activity button
Factorial() procedure, 113
Features, of Flutter, 2–3
Features of Dart, 12
Finally block, 158–159
Firebase database, 329
First application in Flutter, 199–202
First program in Dart, 25
running on browser, 26
using command line, 26
using IDE, 26
FittedBox, 216–217
Fixed length list, 55–56
Flat button, 261–262
floatingActionButton, 241–242
floatingActionButtonLocation, 244
Floating activity button (FAB), 264–265
Flow of control statements, see Control flow statement
Flow statement categories, 82
Dart decision-making statements, 83
Flutter Engine, 203
Flutter SDK
downloading, 8–9
installing, 5–7
FlutterToast.cancel(), 289–290
Fly() function, 135
forEach() function, 67, 73
For in Loop, 96
For Loop in Dart, 94–95
Formal parameter, 104
Forms, 274
creating, 274–276
validation of, 276
Foundation Library, 203
FractionallySizedBox, 217
Function in Dart, 101
with an argument and a return value, 105
calling a function, 103
function benefits, 102
function defining, 102–103
with no parameter and return value, 105–106
with no parameter and without a return value, 106–107
with parameter and without a return value, 107
passing arguments to the function, 103–104
return a value from the function, 104
Fundamental Darts program, 17–18
G
Generators in Dart, 176
async* keyword, 179
asynchronous generators, 177–178
sync* keyword, 178
synchronous generator, 176–177
yield keyword, 178
Generic map, 169
GestureDetector widget, 228–229
Gestures in Flutter, 225, 226
drag, 227
GestureDetector widget, 228–229
long press, 227
multiple gesture, example of, 229–231
pan, 227
pinch, 227
pointers, 225–226
tap, 226
Getter, defining, 147
Git, installing, 5
Google Maps, 327
Google’s Flutter, 4
Grid lists, creating, 284–285
GridView widget, 284
Growable list, 56–57
H
HashMap class, 167
“Helloo World” program, 25
Hierarchical inheritance, 136–137
History, of Flutter
audience, 4
prerequisite, 4
problems, 4
Horizontal drag, 227
Horizontal list, creating, 286
I
IconButton, 268–269
Icons in flutter, 277
icon widget attributes, 277–278
If else-if statement, 87
nested if-else statement, 89–91
If-else statement, 85–87
If statements, 84–85
Images in flutter, 278
display images from internet, 280–281
displaying, 278–280
Implicit super, 138
Indeterminate progress bar, 297
Infinite while loop, 97
Inheritance in Dart, 132
hierarchical inheritance, 136–137
multilevel inheritance, 135–136
single level inheritance, 134–135
InkWell button, 269–270
Insert() method, 58–59
InsertAll() method, 59
Installation of Dart, 20
basic Dart syntax, 26
Dart identifiers, 27
string interpolation and Dart printing, 28
block in Dart, 28
command-line options for Dart, 29
enable checked mode, 29
checked mode, 29
production mode, 29–30
first program in Dart, 25
running on browser, 26
using command line, 26
using IDE, 26
line breaks and Dart whitespace, 28
on Linux, 23
apt-get, installation using, 23–24
dart2js, tool of, 25
Dart IED, support of, 25
Debian package, installation of, 24
installation of Dark SDK on Mac, 24
online Dart, editor of, 24–25
semicolon, of Dart, 28
on Windows, 21–23
Installation of Flutter, 5
macOS system requirements, 7
Flutter SDK, downloading, 8–9
Windows system requirements, 5
Flutter SDK, installing, 5–7
Git, installing, 5
Integer value, 33
IntelliJ Idea, 237
Interactive development environments (IDEs), 236
Android Studio, 237
Codemagic, 238
Emacs, 238
IntelliJ Idea, 237
Visual Studio Code, 237–238
Internet, display images from, 280–281
IntrinsicHeight and IntrinsicWidth, 217
Invisible widget, 209
center, 210
column, 209
padding, 210
row, 209–210
scaffold, 210
stack, 211
K
Keywords in Dart, 31–32
L
Languages, 10
Layout a widget, 213
Layout widgets, sorts of, 214
multiple child widgets, 219–222
single child widgets, 214
Align, 215
AspectRatio, 215
Baseline, 215–216
Center, 214
ConstrainedBox, 216
Container, 214
CustomSingleChildLayout, 216
FittedBox, 216–217
FractionallySizedBox, 217
IntrinsicHeight and IntrinsicWidth, 217
LimitedBox, 217
Offstage, 218
OverflowBox, 218–219
Padding, 214
SizedBox, 215
Lexical closure, 109–110
Lexical scope, 108–109
Libraries in Dart, 14, 172
custom libraries, creating, 173
as an example, 174–175
library connecting, 174
library declaration, 174
Dart web, 16
Dart’s runtime, 16–17
importing a library, 172
importing and using a library as an example, 173
library encapsulation, 173
name alias of library, 175–176
native Dart, 16
platforms, 15–16
LimitedBox, 217
LinearProgressIndicator, 296–301
Line breaks and Dart whitespace, 28
Line chart, 309
Linux, installing Dart SDK on, 23
apt-get, installation using, 23–24
dart2js, tool of, 25
Dart IED, support of, 25
Debian package, installation of, 24
installation of Dark SDK on Mac, 24
online Dart, editor of, 24–25
Lists in Dart, 34, 54
Dart iterating list elements, 63
Growable list, 56–57
inserting an element into a list, 57
Add() method, 57–58
AddAll() method, 58
Insert() method, 58–59
InsertAll() method, 59
list properties, 57–58
lists types, 55
fixed length list, 55–56
removing list elements, 61
Remove() Method, 61
RemoveAt() Method, 61–62
RemoveLast() Method, 62
RemoveRange() Method, 62–63
replaceRange(), 60
updating list, 59–60
Lists in Flutter, 281
basic lists, 281–282
grid lists, creating, 284–285
horizontal list, creating, 286
long lists, working with, 283
ListView.builder() constructor, 283
Logical Operators, 43
Logical operator while loop, 98
Long lists, working with, 283
Long press, 227
Loops in Dart, 94
do-while Loop, 98–99
for in Loop, 96
For Loop in Dart, 94–95
infinite while loop, 97
logical operator while loop, 98
nested for loop, 95–96
selection of the Loop, 99
while loop, 97
M
macOS system requirements, 7
Flutter SDK, downloading, 8–9
Main() function, 26, 110
return value in Dart, 110–111
Map in Dart, 69
declaring, 70
using map constructor, 70–71
using map literals, 70
map methods, 72–74
map properties, 71–72
Metadata in Dart, 164–165
Method overriding in Dart, 141
benefit of, 146
example of, 143–145
polymorphism, 142–143
rules of, 146
using super keyword, 145–146
Methods in Dart, 139
class methods, 140
calling, 141
creating, 141
instance methods, 140
calling, 140
creating, 140
MoveNext() method, 166
Multilevel inheritance, 135–136
Multi-line comments, 31
Multiple child widgets, 219–222
Multiple gesture, example of, 229–231
Multiple inheritance, implementing, 151–153
N
Named constructors, 122
Native Dart, 16
Navigation, 325–326
Nested for loop, 95–96
Nested if-else statement, 89–91
No-argument constructor, 121
NotifyListeners() function, 234
Number in Dart, 49
Dart double, 49–50
Dart integer, 49
Parse() method in Dart, 50
number methods, 51
number properties, 51
Number methods, 51
Number properties, 51
NumericOperation() function, 163
O
Object-oriented concepts in Dart, 113
abstract class, 115
class, 114
inheritance, 114
interfaces, 115
object, 114
polymorphism, 115
Offstage, 218
Operators in Dart, 38
operator types, 38
arithmetic operators in Dart, 39
assignment operator, 40–41
Bitwise operators, 43–44
Cascade notation Operators, 45
Conditional Operators, 44–45
Logical Operators, 43
relational operator, 41–42
Type Test Operators, 42–43
unary operators (post and pre), 39–40
Options button, see Radio button
Outline button, 272–274
OverflowBox, 218–219
P
Package, 326
Package manager in Dart, 170–171
Packages in Dart, 169
package manager in Dart, 170–171
read XML string, 171–172
Padding, 214
Pan, 227
Parameterized constructor, 122
Parent class, 133
Parse() method in Dart, 50
number methods, 51
number properties, 51
persistentFooterButton, 242–243
Pie/donut chart, 310–314
Pinch, 227
PointerCancelEvents, 226
PointerDownEvents, 226
PointerMoveEvents, 226
Pointers, 225–226
PointerUpEvents, 226
Popupmenu button, 270–272
print() function, 26, 52
Production mode, 29–30
Progress bar in Flutter, 296
CircularProgressIndicator, 301–302
LinearProgressIndicator, 296–301
R
Radio button, 293–296
Raised button, 263–264
Read XML string, 171–172
Recursion, 111
base condition in, 112
recursive function in Dart, 112
recursive function qualities, 112–113
working of, 112
Relational operator, 41–42
remove() function, 61, 67, 72, 73
RemoveAt() method, 61–62
RemoveLast() method, 62
RemoveRange() method, 62–63
replaceAll(), 54
ReplaceRange(), 60
resizeToAvoidBottomInset, 244
REST-based mobile apps, 328
Return value in Dart, 110–111
RichText widget, 258
Routing, 325–326
Row widget, 250–252
Runes in Dart, 78
String.codeUnitAt() method, 78–79
String.codeUnits property, 79
String.runes property, 79
Runtime of Dart, 16–17
S
Scaffold, 238
appBar, 239
backgroundColor, 242
body, 239–240
bottomNavigationBar, 243–244
drawer, 240–241
endDrawer, 244
floatingActionButton, 241–242
floatingActionButtonLocation, 244
persistentFooterButton, 242–243
primary, 242
resizeToAvoidBottomInset, 244
SDK, see Software Development Kit
Semicolon, 28
Set element, removing, 67
Dart iterating over a set element, 67
Dart remove all set element, 68
Dart Set operations, 68–69
Dart Set properties, 69
TypeCast set to list, 68
SetState() function, 231
Setter, defining, 147–148
Single child widgets, 214
Align, 215
AspectRatio, 215
Baseline, 215–216
Center, 214
ConstrainedBox, 216
Container, 214
CustomSingleChildLayout, 216
FittedBox, 216–217
FractionallySizedBox, 217
IntrinsicHeight and IntrinsicWidth, 217
LimitedBox, 217
Offstage, 218
OverflowBox, 218–219
Padding, 214
SizedBox, 215
Single level inheritance, 134–135
Single-line comments, 30
SizedBox, 215
Slider, 302
properties of, 303–304
slider widget in Flutter, 304–306
Sliver, 327–328
Software Development Kit (SDK), 323
Spawn() method, 183
Splash screen, 326–327
split(), 54
sqflite database, 329
SQLite database, 329
Start() function, 183
StatefulWidget, 211
StatelessWidget, 212
State management, 211, 231
app state, 233
ChangeNotifier, 234
ChangeNotifierProvider, 235
Consumer, 236
ephemeral state, 232–233
StatefulWidget, 211
StatelessWidget, 212
Static keyword in Dart, 126
static method, 127
calling, 128
declaration, 128
static variable in Dart, 126–127
accessing, 127
declaring, 127
Stop() function, 183
String, printing, 52
String.codeUnitAt() method, 78–79
String.codeUnits property, 79
String.runes property, 79
String concatenation, 52
String interpolation, 18, 28, 53
String interpolation and Dart printing, 28
String methods, 54
String properties, 53
substring(), 54
Super constructor in Dart, 137
explicit super, 139
implicit super, 138
Super keyword, using, 129
with constructor, 132
with parent class method, 130–131
with variables, 129–130
Switch, 306
properties of switch widget, 306–308
Switch case statement, 91
benefits of, 94
Symbol in Dart, 74
Dart convert symbol to string, 77
Sync* keyword, 178
Synchronous generator, 176–177
T
Table, 314–316
Tap, 226
Testing in Flutter, 329–331
TextBox, see TextField
TextField, 258–260
Text widget in Flutter, 254
constructor, 255–258
RichText widget, 258
This keyword in Dart, 123
class variable, 125
class variable and instance variable, difference between, 126
instance variable, 125
local variables, 125
Throwing an exception, 159
Toast Notification, 288–290
toList() function, 68
toLowerCase(), 54
toString(), 54
toUpperCase(), 54
trim(), 54
Try/on/catch blocks, 156–158
TypeCast set to list, 68
Typedef in Dart, 161
assigning typedef variable, 161–162
breakpoints, 164
calling function with typedef, 162
complete the program by using, 162–163
creation of breakpoints in WebStorm, 164
debugging in Dart, 164
declaring, 161
as parameter, 163
Type Test Operators, 42–43
U
Unary operators (post and pre), 39–40
Unit testing, 188–189
advantages of, 190
task, 189
V
Variable creation rule, 35
Variable in Dart, 35
Dart variable declaration, 36
declaring the variable as having multiple values, 36–37
default value, 37
final and const, 37
type annotations, 36
variable creation rule, 35
Vertical drag, 227
Visible widget, 206
button, 207
icon, 208
image, 207–208
text, 206
Visual Studio Code (VS Code), 237–238, 324, 325
VS Code IDE, see Visual Studio Code
W
WebStorm, creation of breakpoints in, 164
While loop, 97
Widgets, 203, 204–206
specific widgets design, 203
gestures, 204
layers, 204
state management, 204
tree of, 205
Widget types, 206
invisible widget, 209
center, 210
column, 209
padding, 210
row, 209–210
scaffold, 210
stack, 211
state management widget, 211
StatefulWidget, 211
StatelessWidget, 212
visible widget, 206
button, 207
icon, 208
image, 207–208
text, 206
Windows, installing Dart SDK on, 21–23
Windows system requirements, 5
Flutter SDK, installing, 5–7
Git, installing, 5
Y
Yield keyword, 176, 177, 178