if/else, switch, for, while, break and continue · 6 h
Reusable blocks: parameters, return values, named and optional arguments, arrow functions · 6 h
Store many items: add, remove, sort, map, where, reduce · 6 h
Key-value data and unique collections, plus JSON-like records · 5 h
23 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi
If balance is enough, give cash, else show a message.
A loop calculates the grade for every student in the class.
A loop keeps the game running until the player loses.
Dart checks conditions from top to bottom and runs the first block that is true. else runs when nothing above matched.
void main() {
int marks = 72;
if (marks >= 90) {
print('Grade A+');
} else if (marks >= 60) {
print('Grade B');
} else if (marks >= 33) {
print('Grade C');
} else {
print('Fail');
}
}switch compares one value with many choices. Each case ends with break (Dart adds it for you when the case has code). default handles everything else.
void main() {
int day = 3;
switch (day) {
case 1: print('Monday'); break;
case 3: print('Wednesday'); break;
default: print('Another day');
}
String cmd = 'stop';
switch (cmd) {
case 'go': print('Moving');
case 'stop': print('Stopped');
default: print('Unknown');
}
}for (start; condition; step) repeats a block a known number of times. i is the counter.
int i = 1, test i <= 5, step i++.void main() {
for (int i = 1; i <= 5; i++) {
print('Round $i');
}
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
print('Sum 1..10 = $sum');
}while checks first, then repeats. do-while runs once first, then checks. Use while when you do not know how many times.
void main() {
int n = 1;
while (n <= 3) {
print('while $n');
n++;
}
int k = 10;
do {
print('do-while runs once: $k');
k++;
} while (k < 5);
}break leaves the loop completely. continue skips the rest of this round and goes to the next.
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 3) continue;
if (i == 6) break;
print(i);
}
print('done');
}for (var x in list) visits every item. A loop inside a loop makes rows and columns.
void main() {
for (var city in ['Ranchi', 'Patna', 'Dhanbad']) {
print(city);
}
for (int r = 1; r <= 3; r++) {
String row = '';
for (int c = 1; c <= 3; c++) {
row += '${r * c} ';
}
print(row);
}
}void main() {
int marks = 45;
if (marks >= 33) {
print('Congratulations, you passed!');
} else {
print('Sorry, try again.');
}
}void main() {
for (int i = 1; i <= 10; i++) {
print('Roll no. $i');
}
}void main() {
int n = 7;
for (int i = 1; i <= 10; i++) {
print('$n x $i = ${n * i}');
}
}void main() {
int day = 6;
switch (day) {
case 1: print('Monday - Maths'); break;
case 2: print('Tuesday - Science'); break;
case 6: print('Saturday - Sports'); break;
case 7: print('Sunday - Holiday'); break;
default: print('Regular school day');
}
}void main() {
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
print('Sum of 1 to 100 = $total');
}void main() {
var students = {'Asha': 91, 'Rohit': 67, 'Meena': 38, 'Sonu': 54};
students.forEach((name, m) {
String grade;
if (m >= 90) { grade = 'A+'; }
else if (m >= 75) { grade = 'A'; }
else if (m >= 60) { grade = 'B'; }
else if (m >= 33) { grade = 'C'; }
else { grade = 'Fail'; }
print('${name.padRight(6)} $m $grade');
});
}void main() {
for (int i = 100; i < 200; i++) {
if (i % 17 == 0) {
print('First multiple of 17 above 100 is $i');
break;
}
}
}void main() {
int sumEven = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0) continue;
sumEven += i;
}
print('Sum of even 1..20 = $sumEven');
}void main() {
int rows = 5;
for (int r = 1; r <= rows; r++) {
String line = ' ' * (rows - r) + '*' * (2 * r - 1);
print(line);
}
}void main() {
List<int> primes = [];
for (int n = 2; n <= 50; n++) {
bool isPrime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.add(n);
}
print(primes);
print('Count: ${primes.length}');
}Decide with conditions. First true block runs.
Compare one value against many cases. default for the rest.
Repeat a known number of times with a counter.
Repeat while a condition is true. do-while runs once first.
Leave the loop, or skip to the next round.
Loop inside loop for rows and columns.
calculateGst(price) is written once and used on every bill.
isValidPhone(text) is called from many forms.
addScore(points) is called whenever the player wins.
A function has a return type, a name, parameters in brackets and a body. void means it returns nothing. You call it by writing its name with brackets.
void greet() {
print('Namaste!');
}
void main() {
greet();
greet();
}Parameters are the inputs. return sends a value back to the caller. The return type says what kind of value comes back.
gst(price) is used on every invoice.int add(int a, int b) {
return a + b;
}
double gst(double price) {
return price * 0.18;
}
void main() {
print(add(4, 6));
int r = add(10, 20);
print(r);
print(gst(2000));
}Optional positional: [int x = 1]. Named: {required String name, int age = 18} called as f(name: 'Asha'). Names make calls easy to read.
Text('Hi', style: ...).String hello(String name, [String greeting = 'Hello']) {
return '$greeting, $name';
}
String card({required String name, int age = 18, String city = 'Ranchi'}) {
return '$name, $age, $city';
}
void main() {
print(hello('Asha'));
print(hello('Asha', 'Namaste'));
print(card(name: 'Rohit'));
print(card(name: 'Meena', city: 'Patna', age: 21));
}A one-expression function can use an arrow =>. A function without a name (anonymous) can be stored in a variable.
(int n) => n * 2 means "take n and give back n times 2".int square(int n) => n * n;
void main() {
print(square(9));
var double2 = (int n) => n * 2;
print(double2(21));
var hi = () {
print('anonymous hello');
};
hi();
}Functions are values: pass them to other functions. The receiver calls them back later (a callback). List methods like map and where work this way.
void repeat(int times, void Function(int) action) {
for (int i = 1; i <= times; i++) {
action(i);
}
}
void main() {
repeat(3, (i) => print('Hello number $i'));
var nums = [1, 2, 3, 4, 5, 6];
print(nums.where((n) => n.isEven).toList());
print(nums.map((n) => n * 10).toList());
}A function can call itself (recursion): it needs a stopping rule (base case). A variable made inside a function lives only inside it (scope).
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int counter = 0;
void tick() {
int local = 5;
counter++;
}
void main() {
print(factorial(5));
tick();
tick();
print(counter);
}void greet(String name) {
print('Namaste, $name! Welcome to BrainBit Infotech.');
}
void main() {
greet('Asha');
greet('Rohit');
greet('Meena');
}int square(int n) => n * n;
int cube(int n) => n * n * n;
void main() {
print(square(12));
print(cube(5));
print(square(3) + cube(2));
}bool isEven(int n) {
return n % 2 == 0;
}
void main() {
print(isEven(10));
print(isEven(7));
for (int i = 1; i <= 5; i++) {
print('$i is ${isEven(i) ? 'even' : 'odd'}');
}
}double withGst(double price, [double rate = 18]) {
return price + price * rate / 100;
}
void main() {
print(withGst(1000));
print(withGst(1000, 5));
print(withGst(250.5, 12));
}int biggest(int a, int b, int c) {
int m = a;
if (b > m) m = b;
if (c > m) m = c;
return m;
}
void main() {
print(biggest(12, 45, 31));
print(biggest(90, 8, 8));
}String studentCard({required String name, required int roll, String city = 'Ranchi', double fee = 1500}) {
return '$name | Roll $roll | $city | Rs $fee';
}
void main() {
print(studentCard(name: 'Asha', roll: 1));
print(studentCard(roll: 2, name: 'Rohit', city: 'Patna'));
print(studentCard(name: 'Meena', roll: 3, fee: 1800));
}String gradeOf(int m) {
if (m >= 90) return 'A+';
if (m >= 75) return 'A';
if (m >= 60) return 'B';
if (m >= 33) return 'C';
return 'Fail';
}
void main() {
var marks = [95, 82, 64, 40, 21];
for (var m in marks) {
print('$m -> ${gradeOf(m)}');
}
}void applyTo(List<int> list, int Function(int) rule) {
for (var x in list) {
print('$x -> ${rule(x)}');
}
}
void main() {
applyTo([1, 2, 3], (n) => n * 100);
print('--');
applyTo([10, 20, 30], (n) => n + 5);
}int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
void main() {
List<int> series = [];
for (int i = 0; i < 12; i++) {
series.add(fib(i));
}
print(series);
print('fib(15) = ${fib(15)}');
}import 'dart:math';
double emi(double loan, double yearlyRate, int months) {
double r = yearlyRate / 12 / 100;
return loan * r * pow(1 + r, months) / (pow(1 + r, months) - 1);
}
double totalInterest(double loan, double yearlyRate, int months) {
return emi(loan, yearlyRate, months) * months - loan;
}
String money(double v) => 'Rs ${v.toStringAsFixed(2)}';
void main() {
for (int years in [1, 3, 5]) {
int m = years * 12;
print('$years yr: EMI ${money(emi(500000, 9, m))}, interest ${money(totalInterest(500000, 9, m))}');
}
}A named reusable block: write once, call many times.
Inputs. return gives back an output.
[x = 1] and {required name} make calls flexible.
One-expression shortcut.
Pass a function into another function.
A function calling itself with a base case.
The cart is a list of products. Add, remove and total them.
A phone keeps a sorted list of names.
Scores are sorted from highest to lowest.
A list is written in square brackets. Positions start at 0. first, last, length help.
List<int> means "a list that holds only whole numbers".void main() {
List<String> cities = ['Ranchi', 'Patna', 'Dhanbad'];
print(cities);
print(cities[0]);
print(cities.last);
print(cities.length);
var marks = <int>[70, 85, 92];
print(marks.first);
}add puts an item at the end, insert at a position, remove deletes by value, removeAt by position.
void main() {
var cart = ['Rice'];
cart.add('Dal');
cart.addAll(['Oil', 'Salt']);
cart.insert(1, 'Sugar');
print(cart);
cart.remove('Oil');
cart.removeAt(0);
print(cart);
cart[0] = 'Atta';
print(cart);
}Use for-in, forEach or index loops. isEmpty, contains, indexOf answer questions.
void main() {
var marks = [70, 85, 92, 60];
for (var m in marks) {
print(m);
}
marks.forEach((m) => print('mark: $m'));
print(marks.contains(85));
print(marks.indexOf(92));
print(marks.isEmpty);
}sort() sorts in place. Give it a rule for custom order. reversed flips. sublist cuts a part.
void main() {
var scores = [45, 90, 12, 78, 56];
scores.sort();
print(scores);
scores.sort((a, b) => b.compareTo(a));
print(scores);
print(scores.reversed.toList());
print(scores.sublist(0, 3));
var names = ['Rohit', 'Asha', 'Meena'];
names.sort();
print(names);
}map changes each item. where keeps items that pass a test. reduce and fold combine all into one value. any/every test the whole list.
where = filter in a shopping app; fold = bill total.void main() {
var prices = [100, 250, 80, 400];
print(prices.map((p) => p * 2).toList());
print(prices.where((p) => p > 90).toList());
print(prices.reduce((a, b) => a + b));
print(prices.fold(0, (sum, p) => sum + p));
print(prices.any((p) => p > 300));
print(prices.every((p) => p > 50));
}... spreads one list into another. Inside a list literal you can use if and for. A list can hold lists (a table).
void main() {
var a = [1, 2];
var b = [0, ...a, 3];
print(b);
bool premium = true;
var menu = ['Home', 'Courses', if (premium) 'Certificates'];
print(menu);
var squares = [for (var i = 1; i <= 5; i++) i * i];
print(squares);
var table = [[1, 2], [3, 4]];
print(table[1][0]);
}void main() {
List<int> marks = [72, 85, 91, 64, 78];
print('Marks: $marks');
print('Count: ${marks.length}');
print('First: ${marks.first} Last: ${marks.last}');
print('Second student: ${marks[1]}');
}void main() {
var items = ['Rice', 'Dal'];
items.add('Oil');
items.add('Salt');
print(items);
items.remove('Dal');
print(items);
print('Do we need Oil? ${items.contains('Oil')}');
}void main() {
var daily = [1200, 950, 1800, 700, 1500];
int total = 0;
for (var d in daily) {
total += d;
}
print('Week sales: Rs $total');
print('Average : Rs ${total / daily.length}');
}void main() {
var scores = [45, 90, 12, 78, 56];
var sorted = [...scores]..sort();
print('Lowest : ${sorted.first}');
print('Highest: ${sorted.last}');
print('Original untouched: $scores');
}void main() {
var steps = ['Open', 'Edit', 'Save', 'Close'];
print(steps.reversed.toList());
for (var s in steps.reversed) {
print(s);
}
}void main() {
var players = ['Asha', 'Rohit', 'Meena', 'Sonu'];
var scores = [450, 720, 610, 520];
var order = List.generate(players.length, (i) => i);
order.sort((a, b) => scores[b].compareTo(scores[a]));
for (int r = 0; r < order.length; r++) {
int i = order[r];
print('#${r + 1} ${players[i].padRight(6)} ${scores[i]}');
}
}void main() {
var prices = [199, 899, 450, 1299, 75, 640];
var costly = prices.where((p) => p > 500).toList();
print('Above 500 : $costly');
var withTax = prices.map((p) => (p * 1.18).round()).toList();
print('With GST : $withTax');
print('Any under 100? ${prices.any((p) => p < 100)}');
}void main() {
var phones = ['98001', '98002', '98001', '98003', '98002'];
var unique = phones.toSet().toList();
print('Original: $phones');
print('Unique : $unique');
print('Duplicates removed: ${phones.length - unique.length}');
}void main() {
var names = ['Rice 5kg', 'Dal 1kg', 'Oil 1L'];
var price = [300, 120, 150];
var qty = [2, 3, 1];
int total = 0;
for (int i = 0; i < names.length; i++) {
int line = price[i] * qty[i];
total += line;
print('${names[i].padRight(9)} ${price[i]} x ${qty[i]} = $line');
}
print('TOTAL = $total');
print('Items = ${qty.fold(0, (a, b) => a + b)}');
}void main() {
var m = [[1, 2, 3], [4, 5, 6]];
print(m);
var t = <List<int>>[];
for (int c = 0; c < m[0].length; c++) {
var row = <int>[];
for (int r = 0; r < m.length; r++) {
row.add(m[r][c]);
}
t.add(row);
}
print(t);
int sum = 0;
for (var row in m) {
for (var x in row) { sum += x; }
}
print('Sum of all = $sum');
}Ordered items in [ ]. Index starts at 0.
add, insert, remove, removeAt, [i] = value.
for-in and forEach visit each item.
sort(), reversed, sublist.
map, where, fold, reduce, any, every.
Spread ..., collection if and for, nested lists.
Name is the key, number is the value.
Each student record is a map: name, roll, marks.
Servers send data as maps and lists. Apps read them.
A map stores key: value pairs in curly brackets. Keys are unique. Look up with map[key]. A missing key gives null.
void main() {
Map<String, String> phone = {
'Asha': '98001',
'Rohit': '98002',
};
print(phone['Asha']);
print(phone['Zoya']);
print(phone.length);
print(phone);
}map[key] = value adds or updates. remove(key) deletes. containsKey checks. putIfAbsent adds only when missing.
void main() {
var stock = {'rice': 50, 'dal': 30};
stock['oil'] = 20;
stock['rice'] = 45;
stock.remove('dal');
stock.putIfAbsent('salt', () => 100);
print(stock);
print(stock.containsKey('oil'));
print(stock['milk'] ?? 0);
}keys, values and entries can be looped. forEach gives key and value together.
void main() {
var marks = {'Asha': 91, 'Rohit': 67, 'Meena': 38};
for (var k in marks.keys) {
print(k);
}
print(marks.values.toList());
marks.forEach((name, m) => print('$name scored $m'));
for (var e in marks.entries) {
print('${e.key} -> ${e.value}');
}
}A Set keeps unique values and ignores duplicates. Use union, intersection and difference to compare two sets.
void main() {
var s = <int>{1, 2, 3, 3, 2};
print(s);
s.add(4);
s.add(1);
print(s.length);
var a = {1, 2, 3, 4};
var b = {3, 4, 5};
print(a.union(b));
print(a.intersection(b));
print(a.difference(b));
print(a.contains(2));
}Data from the internet (JSON) is built from maps and lists. A list of maps is a table where every map is a row.
void main() {
var students = [
{'name': 'Asha', 'marks': 91},
{'name': 'Rohit', 'marks': 67},
];
for (var s in students) {
print('${s['name']} - ${s['marks']}');
}
var courses = {
'Dart': ['Variables', 'Loops'],
'Flutter': ['Widgets'],
};
print(courses['Dart']);
print(courses['Dart']!.length);
}Pick by the question you ask. List: "what is item number 3?" Map: "what is the value for this name?" Set: "is this value present, and no duplicates please."
Order matters, duplicates allowed. Cart items, marks.
Look up by key. Phone book, settings, JSON.
Unique values and fast contains. Tags, visited pages.
void main() {
var phone = {'Asha': '98001', 'Rohit': '98002', 'Meena': '98003'};
print(phone['Rohit']);
phone['Sonu'] = '98004';
print(phone.length);
print(phone);
}void main() {
var stock = {'rice': 50, 'dal': 30, 'oil': 20};
stock['rice'] = stock['rice']! - 8;
stock['dal'] = 0;
stock.remove('oil');
print(stock);
}void main() {
var fees = {'Dart': 3000, 'Flutter': 5000, 'Java': 4000};
fees.forEach((course, fee) {
print('${course.padRight(8)} Rs $fee');
});
print('Total: Rs ${fees.values.fold(0, (a, b) => a + b)}');
}void main() {
var visits = ['Ranchi', 'Patna', 'Ranchi', 'Gaya', 'Patna'];
var cities = visits.toSet();
print(cities);
print('Unique cities: ${cities.length}');
}void main() {
var users = {'asha': 'pass1', 'rohit': 'pass2'};
String name = 'asha';
if (users.containsKey(name)) {
print('Welcome $name');
} else {
print('Unknown user');
}
print(users.containsKey('zoya'));
}void main() {
String text = 'dart is fun and dart is easy';
var count = <String, int>{};
for (var w in text.split(' ')) {
count[w] = (count[w] ?? 0) + 1;
}
print(count);
count.forEach((w, c) => print('$w : ${'#' * c}'));
}void main() {
var students = [
{'name': 'Asha', 'class': 8, 'marks': 91},
{'name': 'Rohit', 'class': 8, 'marks': 67},
{'name': 'Meena', 'class': 9, 'marks': 38},
{'name': 'Sonu', 'class': 9, 'marks': 72},
];
for (var s in students) {
print('${s['name']} (class ${s['class']}): ${s['marks']}');
}
var toppers = students.where((s) => (s['marks'] as int) >= 70).map((s) => s['name']).toList();
print('Toppers: $toppers');
}void main() {
var dart = {'Asha', 'Rohit', 'Meena', 'Sonu'};
var flutter = {'Rohit', 'Sonu', 'Kiran'};
print('Both courses : ${dart.intersection(flutter)}');
print('Any course : ${dart.union(flutter)}');
print('Only Dart : ${dart.difference(flutter)}');
print('Total unique : ${dart.union(flutter).length}');
}void main() {
var people = [
['Asha', 'Ranchi'], ['Rohit', 'Patna'], ['Meena', 'Ranchi'],
['Sonu', 'Gaya'], ['Kiran', 'Patna'],
];
var byCity = <String, List<String>>{};
for (var p in people) {
byCity.putIfAbsent(p[1], () => []).add(p[0]);
}
byCity.forEach((city, names) {
print('$city (${names.length}): ${names.join(', ')}');
});
}void main() {
var stock = {'Rice': 40, 'Dal': 12, 'Oil': 6, 'Salt': 25};
var sales = [['Rice', 15], ['Oil', 4], ['Dal', 3], ['Oil', 1]];
for (var s in sales) {
stock[s[0] as String] = stock[s[0]]! - (s[1] as int);
}
stock.forEach((item, q) {
String flag = q < 5 ? ' <-- LOW STOCK' : '';
print('${item.padRight(6)} $q$flag');
});
print('Total items: ${stock.values.reduce((a, b) => a + b)}');
}Key: value pairs. Look up with map[key].
map[k] = v, remove, containsKey, putIfAbsent.
keys, values, entries, forEach.
Unique values. union, intersection, difference.
Lists of maps look like JSON from servers.
List by position, Map by key, Set for uniqueness.