0% found this document useful (0 votes)
27 views34 pages

Unit 2 Mad

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 34

BHAGWAN MAHAVIR UNIVERSITY

BHAGWAN MAHAVIR POLYTECHNIC


READING MATERIAL
Mobile App Development (1030106601)
6TH SEM

UNIT-II Introduction to Dart

Dart Programming
o Dart is an open-source, general-purpose, object-oriented programming language with C-style
syntax developed by Google in 2011.
o The purpose of Dart programming is to create a frontend user interface for the web and mobile
apps.
o It is under active development, compiled to native machine code for building mobile apps,
inspired by other programming languages such as Java, JavaScript, C#, and is Strongly Typed.
o Dart is a compiled language so you cannot execute your code directly; instead, the compiler
parses it and transfers it into machine code.
o It supports most of the common concepts of programming languages like classes, interfaces,
functions, unlike other programming languages.
o Dart language does not support arrays directly. It supports collection, which is used to replicate
the data structure such as arrays, generics, and optional typing.

Syntax
Syntax defines a set of rules for writing programs.
A Dart program is composed of −
● Variables and Operators
● Classes
● Functions
● Expressions and Programming Constructs
● Decision Making and Looping Constructs
● Comments
● Libraries and Packages
● Typedefs
● Data structures represented as Collections / Generics

Let us start with “Hello World” example −


main() {

Page 1
print("Hello World!");
}
The main() function is a predefined method in Dart.
This method acts as the entry point to the application. A Dart script needs the main() method for
execution. print() is a predefined function that prints the specified string or value to the standard output
i.e. the terminal.
The output of the above code will be −
Hello World!

Execute a Dart Program


You can execute a Dart program in two ways −
● Via the terminal
● Via the WebStorm IDE

Via the Terminal


To execute a Dart program via the terminal −
● Navigate to the path of the current project
● Type the following command in the Terminal window

Save dart file as file_name.dart

Via the WebStorm IDE


To execute a Dart program via the WebStorm IDE −
● Right-click the Dart script file on the IDE. (The file should contain the main() function to
enable execution)
● Click on the „Run <file_name>‟ option. A screenshot of the same is given below −

Page 2
Dart Command-Line Options
Dart command-line options are used to modify Dart Script execution. Common command line options
for Dart include the following −

Sr.No Command-Line Option & Description

1 -c or --c
Enables both assertions and type checks (checked mode).

2 --version
Displays VM version information.

3 --packages <path>
Specifies the path to the package resolution configuration file.

4 -p <path>
Specifies where to find imported libraries. This option cannot be used with --packages.

5 -h or --help
Displays help.

Enabling Checked Mode


Dart programs run in two modes namely −
● Checked Mode
● Production Mode (Default)

Page 3
It is recommended to run the Dart VM in checked mode during development and testing, since it adds
warnings and errors to aid development and debugging process. The checked mode enforces various
checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the
script-file name while running the script.
However, to ensure performance benefit while running the script, it is recommended to run the script in
the production mode.
Consider the following Test.dart script file −

void main() {
int n = "hello";
print(n);
}
Run the script by entering −
dart Test.dart

Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The
script will result in the following output −
hello

Now try executing the script with the "- - checked" or the "-c" option −
dart -c Test.dart
Or,
dart - - checked Test.dart
The Dart VM will throw an error stating that there is a type mismatch.
Unhandled exception:
type 'String' is not a subtype of type 'int' of 'n' where
String is from dart:core
int is from dart:core
#0 main (file:///C:/Users/Administrator/Desktop/test.dart:3:9)
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261)
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

Identifiers in Dart

Page 4
Identifiers are names given to elements in a program like variables, functions etc. The rules for
identifiers are −
Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.
● Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($).
● Identifiers cannot be keywords.
● They must be unique.
● Identifiers are case-sensitive.
● Identifiers cannot contain spaces.

The following tables lists a few examples of valid and invalid identifiers −

Valid identifiers Invalid identifiers

firstName Var

first_name first name

num1 first-name

$result 1number

Keywords in Dart
Keywords have a special meaning in the context of a language. The following table lists some keywords
in Dart.

abstract 1 Continue false New this

as 1 Default final Null throw

Assert deferred 1 finally operator 1 true

async 2 Do for part 1 try

async* 2 dynamic 1 get 1 Rethrow typedef 1

await 2 Else if Return var

Break Enum implements 1 set 1 void

Case export 1 import 1 static 1 while

Page 5
Catch external 1 in Super with

Class Extends is Switch yield 2

Const factory 1 library 1 sync* 2 yield* 2

Whitespace and Line Breaks


Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines
freely in your program and you are free to format and indent your programs in a neat and consistent way
that makes the code easy to read and understand.
Dart is Case-sensitive
Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters.
Statements end with a Semicolon
Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A
single line can contain multiple statements. However, these statements must be separated by a
semicolon.

Comments in Dart
Comments are a way to improve the readability of a program. Comments can be used to include
additional information about a program like author of the code, hints about a function/ construct etc.
Comments are ignored by the compiler.
Dart supports the following types of comments −
● Single-line comments ( // ) − Any text between a "//" and the end of a line is treated as a
comment
● Multi-line comments (/* */) − These comments may span multiple lines.

Example
// this is single line comment

/* This is a
Multi-line comment
*/

Object-Oriented Programming in Dart

Page 6
Dart is an Object-Oriented language. Object Orientation is a software development paradigm that
follows real-world modelling. Object Orientation considers a program as a collection of objects that
communicate with each other via mechanism called methods.
● Object − An object is a real-time representation of any entity. As per Grady Brooch, every
object must have three features −
o State − described by the attributes of an object.
o Behavior − describes how the object will act.
o Identity − a unique value that distinguishes an object from a set of similar
such objects.
● Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates
data for the object.
● Method − Methods facilitate communication between objects.

Example: Dart and Object Orientation


class TestClass {
void disp() {
print("Hello World");
}
}
void main() {
TestClass c = new TestClass();
c.disp();
}
The above example defines a class TestClass. The class has a method disp(). The method prints the
string “Hello World” on the terminal. The new keyword creates an object of the class. The object
invokes the method disp().
The code should produce the following output −
Hello World

Data Example Descriptions


Type

String String myName It holds text. In this, you can use single or double quotation marks. Once
= 'priya'; you decide the quotation marks, you should have to be consistent with your
choice.

num, int age = 25; The num data type stands for a number. Dart has two types of numbers:
int, double price = ● Integer (It is a number without a decimal place.)
double 125.50; ● Double (It is a number with a decimal place.)

Page 7
Boolean bool var_name It uses the bool keyword to represent the Boolean value true and false.
= true;
Or
bool var_name
= false;

Object Person = Generally, everything in Dart is an object (e.g., Integer, String). But an
Person() object can also be more complex.

A List is an ordered group of objects. The List data type in Dart is


List synonymous to the concept of an array in other programming
languages.

Map The Map data type represents a set of values as key-value pairs

Variables
Variables are the namespace in memory that stores values. The name of a variable is called as
identifiers. A variable must be declared before it is used.
They are the data containers, which can store the value of any type. For example:
1. var myAge = 25;

Here, myAge is a variable that stores an integer value 25. We can also give it int and double. However,
Dart has a feature Type Inference, which infers the types of values. So, if you create a variable with a
var keyword, Dart can infer that variable as of type integer.

The syntax for declaring a variable is as given below −


var name = 'Smith';

All variables in dart store a reference to the value rather than containing the value. The variable called
name contains a reference to a String object with a value of “Smith”.

Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures
that a variable holds only data specific to a data type. The syntax for the same is given below −
String name = 'Smith';

Page 8
int num = 10;

Consider the following example −


void main() {
String name = 1;
}
The above snippet will result in a warning since the value assigned to the variable doesn‟t match the
variable‟s data type.
Output
Warning: A value of type 'String' cannot be assigned to a variable of type 'int'

All uninitialized variables have an initial value of null. This is because Dart considers all values as
objects. The following example illustrates the same −

void main() {
int num;
print(num);
}
Output
Null

The dynamic keyword


Variables declared without a static type are implicitly declared as dynamic. Variables can be also
declared using the dynamic keyword in place of the var keyword.
The following example illustrates the same.
void main() {
dynamic x = "priya";
print(x);
}

Output
priya

Final and Const


The final and const keyword are used to declare constants. Dart prevents modifying the values of a
variable declared using the final or const keyword. These keywords can be used in conjunction with the
variable‟s data type or instead of the var keyword.
The const keyword is used to represent a compile-time constant. Variables declared using the const
keyword are implicitly final.

Page 9
Syntax: final Keyword
final variable_name
OR
final data_type variable_name

Syntax: const Keyword


const variable_name
OR
const data_type variable_name

Example – final Keyword


void main() {
final val1 = 12;
print(val1);
}

Output
12

Example – const Keyword


void main() {
const pi = 3.14;
const area = pi*12*12;
print("The output is ${area}");
}
The above example declares two constants, pi and area, using the const keyword. The area variable‟s
value is a compile-time constant.
Output
The output is 452.15999999999997

Note − Only const variables can be used to compute a compile time constant. Compile-time constants
are constants whose values will be determined at compile time
Besides variable, Functions are another core feature of any programming language.

Functions
Functions are a set of statements that performs a specific task. They are organized into the logical blocks
of code that are readable, maintainable, and reusable.

The function declaration contains the function name, return type, and parameters. The following
example explains the function used in Dart programming.
The syntax for defining a standard function is given below −
function_name() {

Page 10
//statements
}
OR
void function_name() {
//statements
}
A function must be called to execute it. This process is termed as function invocation.
Syntax
function_name()
The following example illustrates how a function can be invoked −
void main() {
test();
}
test() {
//function definition
print("function called");
}
Functions may also return value along with the control, back to the caller. Such functions are called
as returning functions.
Syntax
return_type function_name(){
//statements
return value;
}
● The return_type can be any valid data type.
● The return statement is optional. I not specified the function returns null;
● The data type of the value returned must match the return type of the function.
● A function can return at the most one value. In other words, there can be only one return
statement per function.

//Function declaration
num addNumbers(num a, num b) {
// Here, we use num as a type because it should work with int and double both.
return a + b;
}

var price1 = 29.99;


var price2 = 20.81;
var total = addNumbers(price1, price2);
var num1 = 10;
var num2 = 45;
var total2 = addNumbers(num1, num2);

Page 11
Operators
Dart language supports all operators, as you are familiar with other programming languages such as C,
Kotlin, and Swift. The operator's name is listed below:
● Arithmetic Operators
● Equality and Relational Operators
● Type test Operators
● Bitwise Operators
● Assignment Operators
● Logical Operators

Arithmetic Operators
The following table shows the arithmetic operators supported by Dart.

Sr.No Operators & Meaning

1 +
Add

2 −
Subtract

3 -expr
Unary minus, also known as negation (reverse the sign of the expression)

4 *
Multiply

5 /
Divide

6 ~/
Divide, returning an integer result

7 %
Get the remainder of an integer division (modulo)

8 ++
Increment

Page 12
9 --
Decrement

Equality and Relational Operators


Relational Operators tests or defines the kind of relationship between two entities. Relational operators
return a Boolean value i.e. true/ false.
Assume the value of A is 10 and B is 20.

Operator Description Example

> Greater than (A > B) is False

< Lesser than (A < B) is True

>= Greater than or equal to (A >= B) is False

<= Lesser than or equal to (A <= B) is True

== Equality (A==B) is False

!= Not equal (A!=B) is True

Type test Operators


These operators are handy for checking types at runtime.

Operator Meaning

Is True if the object has the specified type

is! False if the object has the specified type

Bitwise Operators
The following table lists the bitwise operators available in Dart and their role −

Operator Description Example

Bitwise AND a&b Returns a one in each bit position for which the
corresponding bits of both operands are ones.

Bitwise OR a|b Returns a one in each bit position for which the
corresponding bits of either or both operands are ones.

Page 13
Bitwise XOR a^b Returns a one in each bit position for which the
corresponding bits of either but not both operands are
ones.

Bitwise NOT ~a Inverts the bits of its operand.

Left shift a≪b Shifts a in binary representation b (< 32) bits to the left,
shifting in zeroes from the right.

right shift a≫b Shifts a in binary representation b (< 32) bits to the right,
discarding bits shifted off.
Assignment Operators
The following table lists the assignment operators available in Dart.

Sr.No Operator & Description

1 =(Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex:C = A + B will assign the value of A + B into C

2 ??=
Assign the value only if the variable is null

3 +=(Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A

4 ─=(Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C – A

5 *=(Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

Page 14
6 /=(Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.

Note − Same logic applies to Bitwise operators, so they will become ≪=, ≫=, ≫=, ≫=, |= and ^=.
Logical Operators
Logical operators are used to combine two or more conditions. Logical operators return a Boolean value.
Assume the value of variable A is 10 and B is 20.

Operator Description Example

&& (A > 10
And − The operator returns true only if all the expressions specified
&& B >
return true
10) is
False.

|| (A > 10 ||
OR − The operator returns true if at least one of the expressions
B > 10)
specified return true
is True.

! !(A >
NOT − The operator returns the inverse of the expression‟s result. For
10) is
E.g.: !(7>5) returns false
True.

Conditional Expressions
Dart has two operators that let you evaluate expressions that might otherwise require ifelse statements −
condition ? expr1 : expr2
If condition is true, then the expression evaluates expr1 (and returns its value); otherwise, it evaluates
and returns the value of expr2.
expr1 ?? expr2
If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2
Example
The following example shows how you can use conditional expression in Dart −
void main() {
var a = 10;
var res = a > 12 ? "value greater than 10" : "value lesser than or equal to 10";
print(res);
}
It will produce the following output −

Page 15
value lesser than or equal to 10
Example
Let‟s take another example −
void main() {
var a = null;
var b = 12;
var res = a ?? b;
print(res);
}
It will produce the following output −
12

Decision Making and Loops


The decision-making is a feature that allows you to evaluate a condition before the instructions are
executed. The Dart language supports the following types of decision-making statements:
● If statement
● If-else statement
● Switch statement

Example
1. void main() {
2. var num = 12;
3. if (num % 2 = = 0) {
4. print("Number is Even.");
5. } else {
6. print("Number is Odd.");
7. }
8. }

Loops are used to execute a block of code repeatedly until a specified condition becomes true. Dart
language supports the following types of loop statements:
● for
● for..in
● while
● do..while
The below diagram explains it more clearly.

Dart Function with optional parameters


The following defines the greet() function that accepts name and title and returns a greeting message:

String greet(String name, String title) {


return 'Hello $title $name!';

Page 16
}

When calling the greet() function, you need to pass two arguments like this:
String greet(String name, String title) {
return 'Hello $title $name!';
}

void main() {
print(greet('John', 'Professor'));
}
Output:
Hello Professor John!

However, not everyone has a title. Therefore, the title parameter should be optional. To make a
parameter optional, you use a square bracket. For example:

String greet(String name, [String title = '']) {


if (title.isEmpty) {
return 'Hello $name';
}
return 'Hello $title $name!';
}

In this example, we use square brackets to make the title parameter optional. Also, we assign a default
value to the title parameter.

Inside the function body, we return the corresponding greeting message based on whether the title is
empty or not.

When calling the greet() function, you can omit the title if the person doesn‟t have it like the following
example:

String greet(String name, [String title = '']) {


if (title.isEmpty) {
return 'Hello $name';
}
return 'Hello $title $name!';
}

void main() {
print(greet('John'));
}
Or you can pass the title to the greet() function:
String greet(String name, [String title = '']) {
if (title.isEmpty) {
return 'Hello $name';

Page 17
}
return 'Hello $title $name!';
}

void main() {
print(greet('John'));
print(greet('Alice', 'Professor'));
}

It‟s important to notice that Dart requires the optional parameters to appear last in the parameter list.
Also, a function can have multiple optional parameters.
Summary
● Use the square brackets [] to make one or more parameters optional.
● Specify a default value for the optional parameters.
Dart function with named parameters
The following defines a function called greet() that accepts name and title and returns a greeting
message:

String greet(String name, String title) {


return 'Hello $title $name!';
}
When calling the greet() function, you need to pass the name and title arguments in the right order. In
other words, you need to pass the name as the first argument and the title as the second argument:

String greet(String name, String title) {


return 'Hello $title $name!';
}

void main() {
print(greet('Alice', 'Professor'));
}
Output:
Hello Professor Alice!

If you pass the arguments in the wrong order, the function will not work properly. For example:

String greet(String name, String title) {


return 'Hello $title $name';
}

void main() {
print(greet('Professor', 'Alice'));
}
Output:
Hello Alice Professor!

Page 18
The name and title are called positional parameters.
If a function uses positional parameters, when calling it, you need to provide the arguments that follow
the order of the parameters.
Also, when looking at the following function call, you may not understand it fully:
greet('Alice', 'Professor')

To resolve this, you can use named parameters. Named parameters make the meaning of parameters
clear in the function calls.
To define named parameters, you surround them with curly braces. For example:

string greet(String name,{String title=‟‟}){


if (title.isEmpty) {
return 'Hello $name!';
}
return 'Hello $title $name!';
}
In this example, we change the title from a positional parameter to a named parameter. The named
parameter is also optional. Therefore, you need to assign a default value to it.
Also, when calling the greet() function, you need to specify the parameter name like this:

String greet(String name, {String title = ''}) {


if (title.isEmpty) {
return 'Hello $name!';
}
return 'Hello $title $name!';
}

void main() {
print(greet('Alice', title: 'Professor'));
}

This example calls the greet() function and specifies the named parameter:
greet('Alice', title: 'Professor')
A function can have either optional parameters or named parameters, but not both.

Making named parameters required


The named parameters are optional by default. It means that you need to specify the default values for
the named parameters when defining the function. For example:

void connect(String host,


{int port = 3306, String user = 'root', String password = ''}) {
print('Connecting to $host on $port using $user/$password...');
}

void main() {
connect('localhost');

Page 19
}
Output:
Connecting to localhost on 3306 using root/...

To make a named parameter required, you add the required keyword in front and remove the default
value.

The following example makes the user and password parameters required:

void connect(String host,{int port = 3306, required String user, required String password}) {

print('Connecting to $host on $port using $user/$password...');


}

void main() {
connect('localhost', user: 'root', password: 'secret');
}
Summary
● Use Dart named parameters to make the parameters clear in function calls.
● Use {} to surround the named parameters.
● By default, named parameters are optional. Use the required keyword to make them required.
● Specify the parameter names when calling a function with named parameters.

Dart Functions are First-class Citizens

In Dart, functions are first-class citizens. This means that you can treat a function as a value of other
types. So you can:
● Assign a function to a variable.
● Pass a function to another function as an argument.
● Return a function from a function.

Assigning a function to a variable


The following example shows how to assign a function to a variable:
int add(int x, int y) {
return x + y;
}

void main() {
var fn = add;
var result = fn(10, 20);
print(result);
}
Output:
30

Page 20
How it works.
First, define the add() function that accepts two integers and returns the sum of them:

int add(int x, int y) {


return x + y;
}

Second, assign the add function name to the fn variable:

var fn = add;

Note that you don‟t use the parentheses () after the add function name.
Third, call the add function via the fn variable and assign the return value to the result variable:

var result = fn(10, 20);

Finally, display the result:


print(result);
Passing a function to another function as an argument
The following program illustrates how to pass a function to another function as an argument:
bool isOddNumber(int x) {
return x % 2 != 0;
}

bool isEvenNumber(int x) {
return x % 2 == 0;
}

void show(Function fn) {


for (int i = 0; i < 10; i++) {
if (fn(i)) {
print(i);
}
}
}

void main() {
print("Even numbers:");
show(isEvenNumber);

print("Odd numbers:");
show(isOddNumber);
}
Output:
Even numbers:
0

Page 21
2
4
6
8
Odd numbers:
1
3
5
7
9

How it works.
First, define isOddNumber() function that returns true if a number is odd:
bool isOddNumber(int x) {
return x % 2 != 0;
}
Next, define isEvenNumber() function that returns true if a number is even:

bool isEvenNumber(int x) {
return x % 2 == 0;
}

Then, define the show() function that accepts a function as an argument. Note that all functions have the
type Function:

void show(Function fn) {


for (int i = 0; i < 10; i++) {
if (fn(i)) {
print(i);
}
}
}

Inside the show() function, iterate from 0 to 10. In each iteration, display the value if it makes the result
of the fn() true.

After that, call the show function and pass the isEvenNumber as an argument:

print("Even numbers:");
show(isEvenNumber);

This function call will display all the even numbers from 0 to 9.
Finally, call the show() function and pass the isOddNumber as an argument:

print("Odd numbers:");
show(isOddNumber);

Page 22
This function call will display all odd numbers from 0 to 9.

Returning a function from a function


The following example illustrates how to return a function from a function:
add(int x, int y) {
return x + y;
}

subtract(int x, int y) {
return x - y;
}

Function calculation(String op) {


if (op == '+') return add;
if (op == '-') return subtract;
return add;
}

void main() {
var fn = calculation('+');
print(fn(10, 20));

fn = calculation('-');
print(fn(30,20));
}
Output:
30
10

How it works.
First, define the add() function that returns the sum of two integers:

add(int x, int y) {
return x + y;
}
Next, define the subtract function that returns the subtraction of two integers:

subtract(int x, int y) {
return x - y;
}
Then, define calculation() function that returns the add function if the argument is '+' or the subtract
function if the argument is '-':

Function calculation(String op) {


if (op == '+') return add;

Page 23
if (op == '-') return subtract;
return add;
}

After that, call the calculation function, and assign the result to the fn variable, and call the function via
the fn variable:

var fn = calculation('+');
print(fn(10, 20));

This code displays 30 because the calculation() function returns the add function.
Finally, call the calculation() function, assign the result to the fn variable, and call the function via the fn
variable:

fn = calculation('-');
print(fn(30, 20));

This code display 10 because the calculation() function returns the subtract function.
Summary
● Dart functions are first-class citizens means that you can assign a function to a variable, pass a
function to another function as an argument, and return a function from another function.

Higher Order Functions


In dart programming language can accept a function as an argument, this type of functions is called
higher order functions.
for example :-
void printUser(String Function() getUser)
{
// getting user maybe it's from api like etc.
String user = getUser();

// and print the user.


print(user);
}

Here the PrintUser is a higher order function because printUser function is accept a function named
getUser as an argument, that void printUser(String Function() getUser){ }.

The functions are first class citizens in dart programming language because, They can be assigned to a
variable, passed as an argument to another function, returned from a function, stored in other Data
collections, and created in any scope.

What is callback function?

// this function called higher order function.

Page 24
void higherOrderFunction(String Function() callbackFunction)
{

// this function called callback function generally.


callbackFunction();

A function passed as the argument of another function , this kind of function is called callback functions
and which function is accepted the callback function that function is called higher order function.

Dart anonymous functions


An anonymous function is a function that does not have a name.

So far, you learned how to define named functions. If you remove the return type and name from a
named function, you‟ll have an anonymous function.

For example, the following defines the add() function that returns the sum of two integers:

int add(int x, int y) {


return x + y;
}

If you remove the return type (int) and name (add) from add() function, you‟ll have the following
anonymous function:

(int x, int y) {
return x + y;
}

Typically, you assign an anonymous function to a variable and use the variable to call the function. Note
that functions are first-class citizens in Dart.

For example:
void main() {
var sum = (int x, int y) {
return x + y;
};

print(sum(10, 20));
}

Output:
30

How it works.

Page 25
First, define an anonymous function and assign it to the sum variable:
var sum = (int x, int y) {
return x + y;
};

Second, call the function via the sum variable and display the result:
print(sum(10, 20));

In practice, you often pass an anonymous function to another function that accepts a function as an
argument. For example:
void show(fn) {
for (var i = 0; i < 10; i++) {
if (fn(i)) {
print(i);
}
}
}

void main() {
// show even numbers
show((int x) {
return x % 2 == 0;
});
}
Output:
0
2
4
6
8

How it works.
First, define a function show() that accepts a function (fn) as an argument. The show() function iterates
the numbers from 1 to 10 and displays the number if the number makes the fn function true:

void show(fn) {
for (var i = 0; i < 10; i++) {
if (fn(i)) {
print(i);
}
}
}

Second, call the show() function and pass an anonymous function that returns true if the number is an
even number:

Page 26
void main() {
// show even numbers
show((int x) {
return x % 2 == 0;
});
}

The following example illustrates how to define an anonymous function that returns another anonymous
function:
void main() {
var multiplier = (int x) {
return (int y) {
return x * y;
};
};

var doubleIt = multiplier(2);


print(doubleIt(10)); // 20
}

How it works.
First, define an anonymous function and assign it to the multiplier variable:
var multiplier = (int x) {
return (int y) {
return x * y;
};
};

The anonymous function accepts an integer (x) and returns another anonymous function. The returned
anonymous function accepts an integer and returns the multiplication of x and y.

Second, call the multiplier function and assign the result to the doubleIt variable:

var doubleIt = multiplier(2);

Since the doubleIt is a function, you can call it to double a number:


print(doubleIt(10)); // 20

Summary
● An anonymous function is a function that doesn‟t have a name.

Dart Arrow Functions


If a function body has only one line, you can use an arrow function with the following syntax to make it
more compact:

returnType functionnName(parameters) => expression;

Page 27
In this syntax, the return type of the function must match the type of the value returned by the
expression.

For example, the following defines the add() function that returns the sum of two integers:
int add(int x, int y) {
return x + y;
}

Since the body of the add() function has only one line, you can convert it to an arrow function like this:

int add(int x, int y) => x + y;

Also, if an anonymous function has one line, you can convert it to an arrow function to make it more
compact:
(parameters) => expression;

For example, the following defines an anonymous function that returns the sum of two integers and
assigns it to the add variable:

void main() {
var add = (int x, int y) {
return x + y;
};

print(add(10, 20));
}
Since the anonymous function has one line, you can use the arrow function syntax like this:

void main() {
var add = (int x, int y) => x + y;

print(add(10, 20));
}
Summary
● Use arrow functions for the functions with one line to make the code more concise.

Extra Notes:
variable_type ? name_of_variable; means that name_of_variable can be null.

variable_type name_of_variable1; means that name_of_variable1 cannot be null and you should
initialize it immediately.

late variable_type name_of_variable2; means that name_of_variable2 cannot be null and you can
initialize it later.

Page 28
late variable_type name_of_variable3; variable_type ? name_of_variable4;

name_of_variable4=some_data; name_of_variable3=name_of_variable4!;// name_of_variable4!


means that you are sure 100% it never will be null

int ? a=null; // OK

int b=null; // b cannot be equal null

Late int c =null; // c cannot be equal null

Late int d;
d=5; //OK

late int d; // if you never initialize it, you'll get exception

int e=5;

int? f=4;
int ? z; e=f!; // OK, You are sure that f never is null e=z!;// You get exception because z is equal null
String Function
The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code
units.
String values in Dart can be represented using either single or double or triple quotes. Single line strings
are represented using single or double quotes. Triple quotes are used to represent multi-line strings.

Syntax
String variable_name = 'value'

OR

String variable_name = ''value''


OR
String variable_name = '''line1
line2'''
OR
String variable_name= ''''''line1
line2''''''

Page 29
void main() {
String str1 = 'this is a single line string';
String str2 = "this is a single line string";
String str3 = '''this is a multiline line string''';
String str4 = """this is a multiline line string""";

print(str1);
print(str2);
print(str3);
print(str4);
}

Output −

this is a single line string


this is a single line string
this is a multiline line string
this is a multiline line string

Example 2

void main() {

int n=1+1;

String str1 = "The sum of 1 and 1 is ${n}";


print(str1);

String str2 = "The sum of 2 and 2 is ${2+2}"; //"${}" can be used to interpolate the value
print(str2);
}
It will produce the following output −
The sum of 1 and 1 is 2

Page 30
The sum of 2 and 2 is 4

String Properties
The properties listed in the following table are all read-only.

Sr.No Property & Description

1 codeUnits
Returns an unmodifiable list of the UTF-16 code units of this string.

2 isEmpty
Returns true if this string is empty.

3 Length
Returns the length of the string including space, tab and newline characters.

Methods to Manipulate Strings


The String class in the dart: core library also provides methods to manipulate strings. Some of these
methods are given below −

Sr.No Methods & Description

1 toLowerCase()
Converts all characters in this string to lower case.
syntax:String.toLowerCase()

2 toUpperCase()
Converts all characters in this string to upper case.
syntax:String.toUpperCase()

Page 31
3 trim()
Returns the string without any leading and trailing whitespace.
Syntax
String.trim()

4 compareTo()
Compares this object to another.
Syntax
compareTo(String other)
Returns an integer representing the relationship between two strings.
0 − when the strings are equal.
1 − when the first string is greater than the second
-1 − when the first string is smaller than the second

5 replaceAll()
Replaces all substrings that match the specified pattern with a given value.
Syntax
String replaceAll(Pattern from, String replace)

Parameters
From − the string to be replaced.
Replace − the substitution string.

6 split()
Splits the string at matches of the specified delimiter and returns a list of substrings.
Syntax
split(Pattern pattern)

Page 32
7 substring()
Returns the substring of this string that extends from startIndex, inclusive, to endIndex,
exclusive.
Syntax
substring(int startIndex, [ int endIndex ])

8 toString()
Returns a string representation of this object.
val.toString()

9 codeUnitAt()
Returns the 16-bit UTF-16 code unit at the given index.

Using StringBuffer in Dart/Flutter


Creating StringBuffer
there is a better way instead of concatenating a string with another string multiple times. You can use
StringBuffer, a class for concatenating strings efficiently. The content will be stored in a buffer first
before converted to a string.
Below is the constructor for creating a new StringBuffer. You can pass an optional argument content
whose value will be set as the initial content.
StringBuffer Properties
bool isEmpty: Whether the buffer is empty.
bool isNotEmpty: Whether the buffer is not empty.
int length: Number of characters in the buffer.
length: The hash code for this object.
length: Runtime type of the object.
StringBuffer Methods
void write(Object obj): Add content of obj (converted to a string) to the buffer.
void writeCharCode(int charCode): Write the string representation of charCode to the buffer.

Page 33
void writeAll(Iterable objects, [String separator = ""]): Add each iterable element to the buffer with
optional separator.
void writeln([Object obj = ""]): Add a newline to the buffer with optional obj (converted to a string)
before the newline.
String toString(): Returns the buffer's content as a string.
void clear(): Clears the buffer.
Void main{
StringBuffer sb = new StringBuffer('Collage: ');//instead of concatenating a string with another string
multiple times. You can use StringBuffer

sb.write('Bhagwan Mahavir');
sb.writeCharCode(46);
sb.writeln('com');
sb.write('Tags: ');
sb.writeAll({'polytechnic', ' vesu-surat'}, ',');

print('length: ${sb.length}');
print('isEmpty: ${sb.isEmpty}');
print('isNotEmpty: ${sb.isNotEmpty}');
print('----------\n${sb.toString()}\n --------- ');

print('CLEAR THE BUFFER');


sb.clear();

print('length: ${sb.length}');
print('isEmpty: ${sb.isEmpty}');
print('isNotEmpty: ${sb.isNotEmpty}');
print('----------\n${sb.toString()}\n --------- ');
}

Page 34

You might also like