Unit 2 Mad
Unit 2 Mad
Unit 2 Mad
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
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!
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 −
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.
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 −
firstName Var
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.
Page 5
Catch external 1 in Super with
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
*/
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.
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.
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.
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;
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
Output
priya
Page 9
Syntax: final Keyword
final variable_name
OR
final data_type variable_name
Output
12
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;
}
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.
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
Operator Meaning
Bitwise Operators
The following table lists the bitwise operators available in Dart and their role −
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.
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.
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
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.
&& (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
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.
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:
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:
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:
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:
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:
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.
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}) {
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.
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.
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:
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:
bool isEvenNumber(int x) {
return x % 2 == 0;
}
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:
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.
subtract(int x, int y) {
return x - y;
}
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 '-':
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.
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.
Page 24
void higherOrderFunction(String Function() 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.
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:
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;
};
};
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:
Summary
● An anonymous function is a function that doesn‟t have a name.
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:
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;
int ? a=null; // OK
Late int d;
d=5; //OK
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
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 −
Example 2
void main() {
int n=1+1;
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.
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.
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.
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('length: ${sb.length}');
print('isEmpty: ${sb.isEmpty}');
print('isNotEmpty: ${sb.isNotEmpty}');
print('----------\n${sb.toString()}\n --------- ');
}
Page 34