Dart Notes
Dart Notes
(Dart Notes)
by
Dr. Osman Khalid
by
Muhammad Rafay Hannan
1
Table of Contents
Dart Programming Language .......................................................................................................... 4
Simple Hello World App ...................................................................................................................... 4
Passing arguments through console ................................................................................................... 4
Variables.............................................................................................................................................. 4
Variable creation and initialization. ................................................................................................ 4
Changing value of variable. ............................................................................................................. 4
We use Object data type, we want to change data type of variable.............................................. 4
Explicit data types ........................................................................................................................... 5
Nullable type ................................................................................................................................... 5
Late variables .................................................................................................................................. 5
Final and Const ................................................................................................................................ 5
Constant .......................................................................................................................................... 6
Variable examples ........................................................................................................................... 6
Conditional expressions: ..................................................................................................................... 6
condition ? expr1 : expr2 ................................................................................................................ 6
expr1 ?? expr2................................................................................................................................. 7
Comments: .......................................................................................................................................... 7
Builtin-Types: ...................................................................................................................................... 7
Strings: ................................................................................................................................................ 7
String concatenation example: ....................................................................................................... 7
Multiline string: ............................................................................................................................... 7
Records ............................................................................................................................................... 8
Lists ................................................................................................................................................... 10
List of Records: .............................................................................................................................. 10
Sets .................................................................................................................................................... 10
Maps ................................................................................................................................................. 11
Objects in Dart resembling javascript objects .................................................................................. 13
List of map objects ............................................................................................................................ 13
Spread operators .............................................................................................................................. 13
Control-flow operators ..................................................................................................................... 14
Patterns ............................................................................................................................................. 15
Variable assignment .......................................................................................................................... 15
Switch statements and expressions .................................................................................................. 16
2
For and for-in loops........................................................................................................................... 17
Functions: .......................................................................................................................................... 17
Named parameters ....................................................................................................................... 18
Optional positional parameters .................................................................................................... 19
The main() function....................................................................................................................... 19
Functions as first-class objects...................................................................................................... 20
Anonymous functions ................................................................................................................... 20
Arrow notation:............................................................................................................................. 21
typdef functions ............................................................................................................................ 22
Error handling. .................................................................................................................................. 22
Classes ............................................................................................................................................... 23
Simple class example .................................................................................................................... 23
No argument constructor ............................................................................................................. 23
One argument generative constructor ......................................................................................... 23
Two argument generative constructor ......................................................................................... 24
Another example of two argument constructor........................................................................... 24
Calling a constructor from another constructor within same class. ............................................. 25
Named constructors ..................................................................................................................... 25
Named arguments in a constructor. ............................................................................................. 26
Immutable objects ........................................................................................................................ 26
Optional arguments to a constructor ........................................................................................... 27
Array of objects ............................................................................................................................. 27
Printing elements in an array ........................................................................................................ 28
Looping through array of objects:................................................................................................. 29
Use continue to skip to the next loop iteration: ...................................................................... 29
Inheritance example. .................................................................................................................... 29
Using parent class constructor in child class................................................................................. 30
Calling named argument constructor from Child class of Parent class ........................................ 30
3
Dart Programming Language
To pass the parameters to the above application using console, run the following command in
console:
Variables
Variable creation and initialization.
var name = 'Bob';
print(name);
4
name = 10;
print(name);
Nullable type
String? name1; // Nullable type. Can be `null` or string.
print(name1); // null
// print(name2); // error
Late variables
When you mark a variable as late but initialize it at its declaration, then the initializer runs the first
time the variable is used. This lazy initialization is handy in a couple of cases:
You're initializing an instance variable, and its initializer needs access to this.
void main() {
description = 'Feijoada!';
print(description);
}
void main() {
final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';
print(name);
print(nickname);
5
// after it is initialized.
}
Constant
void main() {
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere
}
Variable examples
void main() {
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg'
};
print(name);
print(year);
print(antennaDiameter);
print(flybyObjects);
print(image);
Conditional expressions:
condition ? expr1 : expr2
If condition is true, evaluates expr1 (and returns its value); otherwise,
evaluates and returns the value of expr2.
void main()
{
var isPublic = 'public';
var visibility = isPublic=='public' ? 'public' : 'private';
print(visibility);
6
}
expr1 ?? expr2
If expr1 is non-null, returns its value; otherwise, evaluates and returns the
value of expr2.
void main()
{
var var1 = null; // or simply write var var1; this defaults to null
var var2 = 10;
Comments:
// single line , /* multi line */, /// for documentation.
Builtin-Types:
Numbers, Strings, Booleans.
Strings:
String concatenation example:
void main() {
var s1 = 'String '
'concatenation'
" works even over line breaks.";
print(s1);
}
Multiline string:
void main() {
var s1 = '''
You can create
multi-line strings like this one.
''';
7
print(s1);
}
Records
Records are an anonymous, immutable, aggregate type. Like other collection types, they let
you bundle multiple objects into a single object. Unlike other collection types, records are
fixed-sized, heterogeneous, and typed.
Records are real values; you can store them in variables, nest them, pass them to and from
functions, and store them in data structures such as lists, maps, and sets.
Example:
void main() {
print(record);
print(record.a);
print(record.b);
dart
Example:
Here ‘first’, “hello”, ‘last’ are positional fields, and others are named.
void main() {
8
print(record.$3);
In a record type annotation, named fields go inside a curly brace-delimited section of type-
and-name pairs, after all positional fields. In a record expression, the names go before each
field value with a colon after:
The names of named fields in a record type are part of the record's type definition, or
its shape. Two records with named fields with different names have different types:
In a record type annotation, you can also name the positional fields, but these names are
purely for documentation and don't affect the record's type:
Example
Example
9
print(point == color); // Prints 'false'. Lint: Equals on unrelated types.
Lists
Perhaps the most common collection in nearly every programming language is the array, or ordered
group of objects. In Dart, arrays are List objects, so most people just call them lists.
Dart list literals are denoted by a comma separated list of expressions or values, enclosed in square
brackets ([]). Here's a simple Dart list:
void main() {
print(list[0]);
}
List of Records:
void main() {
Sets
#
A set in Dart is an unordered collection of unique items. Dart support for sets is provided by set
literals and the Set type.
void main() {
print(halogens.elementAt(0));
print(halogens.elementAt(1));
10
{
print(element);
}
}
To create an empty set, use {} preceded by a type argument, or assign {} to a variable of type Set:
void main() {
void main() {
Maps
In general, a map is an object that associates keys and values. Both keys and values can be any type
of object. Each key occurs only once, but you can use the same value multiple times. Dart support
for maps is provided by map literals and the Map type.
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
Add a new key-value pair to an existing map using the subscript assignment operator ([]=):
11
Dart
Dart
void main() {
void main() {
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
Dart
void main() {
12
}
Add a new key-value pair to an existing map using the subscript assignment operator ([]=):
Dart
print(myObject1);
];
Spread operators
Dart supports the spread operator (...) and the null-aware spread operator (...?) in list, map, and set
literals. Spread operators provide a concise way to insert multiple values into a collection.
For example, you can use the spread operator (...) to insert all the values of a list into another list:
void main() {
13
If the expression to the right of the spread operator might be null, you can avoid exceptions by using
a null-aware spread operator (...?):
void main() {
Control-flow operators
Dart offers collection if and collection for use in list, map, and set literals. You can use these
operators to build collections using conditionals (if) and repetition (for).
Here's an example of using collection if to create a list with three or four items in it:
void main() {
void main() {
print(nav);
}
14
Here's an example of using collection for to manipulate the items of a list before adding them to
another list:
void main() {
Patterns
Destructuring
When an object and pattern match, the pattern can then access the object's data and extract it in
parts. In other words, the pattern destructures the object:
void main() {
Variable assignment
A variable assignment pattern falls on the left side of an assignment. First, it destructures the
matched object. Then it assigns the values to existing variables, instead of binding new ones.
Use a variable assignment pattern to swap the values of two variables without declaring a third
temporary one:
void main() {
15
}
The values that a pattern destructures in a case become local variables. Their scope is only within
the body of that case.
void main() {
int obj = 3;
const first = 2;
const last = 4;
switch (obj) {
// Matches if 1 == obj.
case 1:
print('one');
default:
}
Guard clauses evaluate an arbitrary conditon as part of a case, without exiting the switch if the
condition is false (like using an if statement in the case body would cause).
void main() {
16
var pair=(20,10);
switch (pair) {
case (int a, int b):
if (a > b) print('First element greater');
// If false, prints nothing and exits the switch.
case (int a, int b) when a > b:
// If false, prints nothing but proceeds to next case.
print('First element greater');
case (int a, int b):
print('First element not greater');
}
}
This example uses object destructuring in a for-in loop to destructure the MapEntry objects that
a <Map>.entries call returns:
void main() {
Map<String, int> hist = {
'a': 23,
'b': 100,
};
Functions:
bool isNoble(int atomicNumber) {
return true;
17
}
Although Effective Dart recommends type annotations for public APIs, the function still works if you
omit the types:
isNoble(int atomicNumber) {
return true;
}
For functions that contain just one expression, you can use a shorthand syntax:
Named parameters
Named parameters are optional unless they're explicitly marked as required.
When defining a function, use {param1, param2, …} to specify named parameters. If you don't
provide a default value or mark a named parameter as required, their types must be nullable as their
default value will be null:
void main() {
print("Hello world");
print("$bold $hidden");
To define a default value for a named parameter besides null, use = to specify a default value. The
specified value must be a compile-time constant. For example:
void main() {
print("Hello world");
enableFlags(hidden: false);
}
print("$bold $hidden");
18
Optional positional parameters
Wrapping a set of function parameters in [] marks them as optional positional parameters. If you
don't provide a default value, their types must be nullable as their default value will be null:
void main() {
print("Hello world");
To define a default value for an optional positional parameter besides null, use = to specify a default
value. The specified value must be a compile-time constant. For example:
void main() {
say("Ali", "hello"); // calling with two arguments
}
The file dartapp.dart is in the bin folder. Run the app like this: dart run dartapp.dart 1
test
19
}
void main() {
void main() {
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
print(loudify("hello"));
}
Anonymous functions
Most functions are named, such as main() or printElement(). You can also create a
nameless function called an anonymous function, or sometimes a lambda or closure.
You might assign an anonymous function to a variable so that, for example, you can
add or remove it from a collection.
The following example defines an anonymous function with an untyped parameter, item,
and passes it to the map function. The function, invoked for each item in the list, converts
each string to uppercase. Then in the anonymous function passed to forEach, each
converted string is printed out alongside its length.
void main() {
20
var result = list.map (
(item)
{
return item.toUpperCase();
}
);
print(result);
result.forEach((item) {
print('$item: ${item.length}');
});
/*
// COMBINED FORM
list.map((item) {
return item.toUpperCase();
}).forEach((item) {
print('$item: ${item.length}');
});
*/
Arrow notation:
Example:
void main() {
Example:
void main() {
21
list.map((item) => item.toUpperCase())
.forEach((item) => print('$item: ${item.length}'));
typdef functions
// 1. Define a typedef for a function that takes two numbers and returns their
sum
typedef SumFunction = int Function(int a, int b);
void main() {
// 3. Use the SumFunction type to declare a variable and assign the add
function
SumFunction sum = add;
// 4. Call the function using the variable with the SumFunction type
int result = sum(5, 3); // result will be 8
Error handling.
void main() {
misbehave();
void misbehave() {
try {
dynamic foo = true;
print(foo++);
} catch (e) {
print(e);
}
22
}
Classes
Simple class example
class Point {
double? x; // Declare instance variable x, initially null.
double? y; // Declare y, initially null.
}
void main() {
var point = Point();
point.x = 4; // Use the setter method for x.
print(point.x);
No argument constructor
class Car {
Car() {
print("no argument constructor called");
}
/*
//OR
Car();
*/
void main() {
Car c = Car();
23
void main() {
Car c = Car("Toyota");
print(c.model);
}
class Point {
final double x;
final double y;
void main() {
Point p1 = Point(10, 20);
print("x: ${p1.x}, y: ${p1.y}");
Point p2 = Point(5, 10);
print(p2.distanceTo(p1));
}
class Car {
String? name;
int? age;
Car(name, age){
this.name = '$name' ' Ali';
this.age = age + 30;
}
24
}
void main() {
Car c = Car("Shahid", 45);
print('${c.name} ${c.age}');
Point(int a, int b) {
x = a;
y = b;
}
void main() {
var point1 = Point(3, 4);
var point2 = Point.fromOrigin();
print('${point1.x} ${point1.y}');
print('${point2.x} ${point2.y}');
}
Named constructors
class User {
User.none();
User.withId(this.id);
User.withName(this.name);
User.withidname(this.id, this.name);
25
void main() {
print('${user1.id} ${user1.name}');
print('${user2.id} ${user2.name}');
print('${user3.id} ${user3.name}');
print('${user4.id} ${user4.name}');
void main(){
Person person1 = Person(age: 25); // Specify age first, name is unknown
print('${person1.age} ${person1.name}');
Person person2 = Person(name: "Bob", age: 42); // Specify both in any order
print('${person2.age} ${person2.name}');
Immutable objects
By adding const, the created object is immutable, its content can’t be changed.
class Teacher {
const Teacher(this.name);
final String name;
}
26
void main() {
var teacher = const Teacher("Osman");
print(teacher.name);
void main() {
// Create a Person with name and age
var person1 = Person('Alice', age: 30);
print('${person1.name} ${person1.age}');
Array of objects
class Student {
String name;
int age;
// Constructor
Student(this.name, this.age);
void main() {
27
List<Student> myObjects = [];
String name;
int age;
// Constructor
Student(this.name, this.age);
28
Looping through array of objects:
class Candidate {
final String name;
final int yearsExperience;
Candidate(this.name, this.yearsExperience);
void interview() {
print("$name is being interviewed...");
// Simulate the interview process
print("$name: Interview went well!");
}
}
void main() {
// List of candidates
List<Candidate> candidates = [
Candidate("Alice", 6),
Candidate("Bob", 3),
Candidate("Charlie", 8),
Candidate("David", 4),
];
Inheritance example.
class ParentClass {
void myfunction() {
print("This is parent class function");
}
29
class ChildClass extends ParentClass {
@override
void myfunction() {
super.myfunction();
print("This is child class function");
}
}
void main() {
ChildClass c = ChildClass();
c.myfunction();
}
class Person {
String? name;
int? age;
Person(this.name, this.age);
void main() {
Student student = Student("ABC123");
print(student.name); // Output: Ali
print(student.age); // Output: 34
print(student.regno); // Output: ABC123
}
30
Person({required this.name, required this.age}); // Named arguments
constructor
}
void main(){
Student s = Student(id: "334", name:"Jamal", age:34);
print('${s.id} ${s.name} ${s.age}');
}
31