0% found this document useful (0 votes)
267 views

Dart Notes

Uploaded by

saroun6699
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
267 views

Dart Notes

Uploaded by

saroun6699
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Mobile Application Development

(Dart Notes)
by
Dr. Osman Khalid

Last Updated: 08 November 2024.

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

Simple Hello World App


Create a Dart console application using Visual Studio Code. The following code will be generated.
The calculate() function is defined in lib/dartproject.dart.

import 'package:dartproject/dartproject.dart' as dartproject;

void main(List<String> arguments) {


print('Hello world: ${dartproject.calculate()}!');

Passing arguments through console


import 'package:dartproject/dartproject.dart' as dartproject;

void main(List<String> arguments) {


print('Arguments: $arguments');
}

To pass the parameters to the above application using console, run the following command in
console:

A:\AAA\flutterprojects\dartproject\bin> dart dartproject.dart one two three

Variables
Variable creation and initialization.
var name = 'Bob';
print(name);

Changing value of variable.


var name = 'Bob';
name = 10; // not allowed to change data type
print(name);

The following code will work.

We use Object data type, we want to change data type of variable.


Object name = 'Bob';

4
name = 10;
print(name);

Explicit data types


String name = 'Bob';
print(name);

Nullable type
String? name1; // Nullable type. Can be `null` or string.

String name2; // Non-nullable type. Cannot be `null` but can be 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:

The variable might not be needed, and initializing it is costly.

You're initializing an instance variable, and its initializer needs access to this.

late String description;

void main() {
description = 'Feijoada!';
print(description);
}

Final and Const


A final variable can be set only once; a const variable is a compile-time constant. (Const variables are
implicitly final.)

void main() {
final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';

print(name);
print(nickname);

// name = 'Ali'; // This is error as value of final cannot be changed

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;

var ans = var1 ?? var2;


print(ans);
}

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() {

// Record type annotation in a variable declaration:


({int a, bool b}) record;

// Initialize it with a record expression:


record = (a: 123, b: true);

print(record);
print(record.a);
print(record.b);

Records expressions are comma-delimited lists of named or positional fields, enclosed in


parentheses:

dart

Example:

Here ‘first’, “hello”, ‘last’ are positional fields, and others are named.

void main() {

var record = ('first', a: 2, "hello", b: true, 'last');

print(record.$1); // Prints 'first'


print(record.a); // Prints 2
print(record.b); // Prints true
print(record.$2); // Prints 'last'

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:

// Record type annotation in a variable declaration:


({int a, bool b}) record;

// Initialize it with a record expression:


record = (a: 123, b: true);

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:

({int a, int b}) recordAB = (a: 1, b: 2);


({int x, int y}) recordXY = (x: 3, y: 4);

// Compile error! These records don't have the same type.


// recordAB = recordXY;

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:

(int a, int b) recordAB = (1, 2);


(int x, int y) recordXY = (3, 4);

recordAB = recordXY; // OK.

Example

(int x, int y, int z) point = (1, 2, 3);


(int r, int g, int b) color = (1, 2, 3);

print(point == color); // Prints 'true'.

Example

({int x, int y, int z}) point = (x: 1, y: 2, z: 3);


({int r, int g, int b}) color = (r: 1, g: 2, b: 3);

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() {

var list = [1, 2, 3];

print(list[0]);
}

List of Records:
void main() {

var list = [(id: 1, name:'Ali'), (id: 2, name:'javed')];

for( var item in list) {


print(item.id);
}
}

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.

Here is a simple Dart set, created using a set literal:

void main() {

var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};

print(halogens.elementAt(0));
print(halogens.elementAt(1));

for (var element in halogens)

10
{
print(element);
}
}

To create an empty set, use {} preceded by a type argument, or assign {} to a variable of type Set:

void main() {

var names = <String>{};


// Set<String> names = {}; // This works, too.
// var names = {}; // Creates a map, not a set.

Add items to an existing set using the add() or addAll() methods:

void main() {

var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};


var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);

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

var gifts = {'first': 'partridge'};


gifts['fourth'] = 'calling birds'; // Add a key-value pair

Retrieve a value from a map using the subscript operator ([]):

Dart

void main() {

var gifts = {'first': 'partridge'};


assert(gifts['first'] == 'partridge');

To print all values of map

void main() {

var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};

for(var key in nobleGases.keys) {


print(nobleGases[key]);
}

You can create the same objects using a Map constructor:

Dart

void main() {

var gifts = Map<String, String>();


gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';

var nobleGases = Map<int, String>();


nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';

12
}

Add a new key-value pair to an existing map using the subscript assignment operator ([]=):

Dart

var gifts = {'first': 'partridge'};


gifts['fourth'] = 'calling birds'; // Add a key-value pair

Objects in Dart resembling javascript objects


We can define javascript type objects using Map:

Map<String, String> myObject1 = {


'name': 'Devin',
'hairColor': 'brown',
};

print(myObject1);

List of map objects


var list = [
{'name': 'Kamran', 'color' : 'red'},
{'name': 'Shahid', 'color' : 'blue'},
{'name': 'Zahid', 'color' : 'green'},

];

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() {

var list = [1, 2, 3];


var list2 = [0, ...list];
assert(list2.length == 4);
}

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() {

var list2 = [0, ...?list];


assert(list2.length == 1);

We can modify the map objects using spread operator:

Map<String, String> myObject1 = {


'name': 'Devin',
'hairColor': 'brown',
};

var myObject2 = {...myObject1, 'name':'Kamran'};


print(myObject2);

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() {

bool promoActive = false;


var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];
print(nav);
}

void main() {

var login = "Manager";

var nav = ['Home', 'Furniture', 'Plants', if (login case 'Manager')


'Inventory'];

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() {

var listOfInts = [1, 2, 3];


var listOfStrings = ['#0', for (var i in listOfInts) '#$i'];
//assert(listOfStrings[1] == '#1');
print(listOfStrings);
}

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() {

var numList = [1, 2, 3];


// List pattern [a, b, c] destructures the three elements from numList...
var [a, b, c] = numList;
// ...and assigns them to new variables.
print(a + b + c);

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() {

var (a, b) = ('left', 'right');


(b, a) = (a, b); // Swap.
print('$a $b'); // Prints "right left".

15
}

Switch statements and expressions


Every case clause contains a pattern. This applies to switch statements and expressions, as well as if-
case statements. You can use any kind of pattern in a case.

Case patterns are refutable. They allow control flow to either:

• Match and destructure the object being switched on.

• Continue execution if the object doesn't match.

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');

// Matches if the value of obj is between the


// constant values of 'first' and 'last'.
case >= first && <= last:
print('in range');

// Matches if obj is a record with two fields,


// then assigns the fields to 'a' and 'b'.
case (var a, var b):
print('a = $a, b = $b');

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');
}
}

For and for-in loops


You can use patterns in for and for-in loops to iterate-over and destructure values in a collection.

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,
};

for (var MapEntry(key: key, value: count) in hist.entries) {


print('$key occurred $count times');
}

Can also be written as:

for (var MapEntry(:key, value: count) in hist.entries) {


print('$key occurred $count times');
}

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:

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

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");

enableFlags(); // will assign default null to bold and hidden


enableFlags(bold:true, hidden: true);
}

void enableFlags({bool? bold, bool? hidden}) {

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);
}

void enableFlags({bool bold=true, bool 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");

say("Ali", "hello"); // calling with two arguments


say("Ali", "hello", "laptop"); // calling with optional argument included
}

void say(String from, String msg, [String? device]) {


var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
print(result);
}

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
}

void say(String from, String msg, [String device = 'carrier pigeon']) {


print('$from $msg $device');
}

The main() function


Every app must have a top-level main() function, which serves as the entrypoint to
the app. The main() function returns void and has an
optional List<String> parameter for arguments.

Here's a simple main() function:

The file dartapp.dart is in the bin folder. Run the app like this: dart run dartapp.dart 1
test

// Run the app like this: dart run args.dart 1 test


void main(List<String> arguments) {
print(arguments);

19
}

Functions as first-class objects


You can pass a function as a parameter to another function. For example:

void main() {

var list = [1, 2, 3];

// Pass printElement as a parameter.


list.forEach(printElement);

void printElement(int element) {


print(element);
}

You can also assign a function to a variable, such as:

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() {

const list = ['apples', 'bananas', 'oranges'];

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() {

const list = ['apples', 'bananas', 'oranges'];

print( list.map((item) => item.toUpperCase()) );

Example:

void main() {

const list = ['apples', 'bananas', 'oranges'];

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() {

// 2. Implement a function that matches the SumFunction signature


int add(int a, int b) => a + b;

// 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

print("Sum of 5 and 3 is: $result");


}

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();

One argument generative constructor


class Car {
String model;
Car(this.model);
}

23
void main() {
Car c = Car("Toyota");
print(c.model);
}

Two argument generative constructor


import 'dart:math';

class Point {
final double x;
final double y;

// Sets the x and y instance variables


// before the constructor body runs.
Point(this.x, this.y);

double distanceTo(Point other) {


var dx = x - other.x;
var dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
}

void main() {
Point p1 = Point(10, 20);
print("x: ${p1.x}, y: ${p1.y}");
Point p2 = Point(5, 10);
print(p2.distanceTo(p1));
}

Another example of two argument constructor


If we want to reprocess the variables before assignment to class variables, we can define the
constructor as follows.

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}');

Calling a constructor from another constructor within same class.


class Point {
int? x;
int? y;

Point(int a, int b) {
x = a;
y = b;
}

Point.fromOrigin() : this(10, 20); // Calls the main constructor


}

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);

// we can also place class variables after constructors


int? id;
String? name;

25
void main() {

var user1 = User.none();


var user2 = User.withId(10);
var user3 = User.withName("Javed");
var user4 = User.withidname(10, "Javed");

print('${user1.id} ${user1.name}');
print('${user2.id} ${user2.name}');
print('${user3.id} ${user3.name}');
print('${user4.id} ${user4.name}');

Named arguments in a constructor.


class Person {
String? name;
int age;

Person({required this.age, String? name}) { // Name is optional now


this.name = name ?? "Unknown"; // Default value for name if not provided
}
}

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);

//teacher.name = "Zahid"; //error

Optional arguments to a constructor


class Person {
final String name;
final int? age; // Can be null

// Constructor with optional age parameter


const Person(this.name, {this.age});
}

void main() {
// Create a Person with name and age
var person1 = Person('Alice', age: 30);

// Create a Person with only name (age will be null)


var person2 = Person('Bob');

print('${person1.name} ${person1.age}');

Array of objects
class Student {

String name;
int age;

// Constructor
Student(this.name, this.age);

void main() {

// Create an array (List) of MyObject instances

27
List<Student> myObjects = [];

// Add objects to the array


myObjects.add(Student('Alice', 25));
myObjects.add(Student('Bob', 30));
myObjects.add(Student('Charlie', 22));

// Access and print elements in the array


for (Student obj in myObjects) {
print('Name: ${obj.name}, Age: ${obj.age}');
}
}

Printing elements in an array


class Student {

String name;
int age;

// Constructor
Student(this.name, this.age);

void main(List<String> arguments) {

// Create an array (List) of MyObject instances


List<Student> myObjects = [];

// Add objects to the array


myObjects.add(Student('Alice', 25));
myObjects.add(Student('Bob', 30));
myObjects.add(Student('Charlie', 22));

// Access and print elements in the array


myObjects.where((student) =>
student.name.contains('Alice')).forEach((student)=>print('Name:
${student.name}, Age: ${student.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),
];

// Filter candidates with 5 or more years of experience and conduct


interviews
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
}
Use continue to skip to the next loop iteration:

for (int i = 0; i < candidates.length; i++) {


var candidate = candidates[i];
if (candidate.yearsExperience < 5) {
continue;
}
candidate.interview();
}

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();
}

Using parent class constructor in child class

class Person {

String? name;
int? age;

Person(this.name, this.age);

class Student extends Person { // Explicitly extend the Person class


String? regno;

Student(this.regno, {String? name = "Ali", int? age = 34}) : super(name,


age);
}

void main() {
Student student = Student("ABC123");
print(student.name); // Output: Ali
print(student.age); // Output: 34
print(student.regno); // Output: ABC123
}

Calling named argument constructor from Child class of Parent class


class Person {
String name;
int age;

30
Person({required this.name, required this.age}); // Named arguments
constructor
}

class Student extends Person {


String id;

Student({required this.id, required String name, required int age})


: super(name: name, age: age); // Calling parent constructor with named
arguments
}

void main(){
Student s = Student(id: "334", name:"Jamal", age:34);
print('${s.id} ${s.name} ${s.age}');
}

31

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy