DART PROGRAMMING COURSE · BRAINBIT INFOTECH

Part 2
Logic, Functions and Collections

Module 5: Control Flow: Decisions and Loops

if/else, switch, for, while, break and continue · 6 h

Module 6: Functions

Reusable blocks: parameters, return values, named and optional arguments, arrow functions · 6 h

Module 7: Lists and Iterables

Store many items: add, remove, sort, map, where, reduce · 6 h

Module 8: Maps and Sets

Key-value data and unique collections, plus JSON-like records · 5 h

23 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi

MODULE 5 · PART 2

Control Flow: Decisions and Loops

if/else, switch, for, while, break and continue
You will learn
  • Make decisions with if, else if and else
  • Choose with switch
  • Repeat with for loops
  • Repeat with while and do-while
  • break and continue
  • for-in loops and nested loops
You will build: a grade calculator, a multiplication table and a number guessing helper
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🔀

Where is this used in real apps?

Programs become powerful when they can decide (if) and repeat (loops). A bank app decides if you have enough balance; a school app repeats the same steps for every student.

ATM and banking

If balance is enough, give cash, else show a message.

Result software

A loop calculates the grade for every student in the class.

Games

A loop keeps the game running until the player loses.

Result Card
🎓
Asha - 86%
Grade A
🎓
Rohit - 61%
Grade B
🎓
Meena - 38%
Grade D

if, else if, else

Dart checks conditions from top to bottom and runs the first block that is true. else runs when nothing above matched.

Order matters: put the strictest condition first.
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

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.

Real use: menu choices, day names, order status.
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 loop

for (start; condition; step) repeats a block a known number of times. i is the counter.

Three parts: start 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 and do-while

while checks first, then repeats. do-while runs once first, then checks. Use while when you do not know how many times.

Danger: if the condition never becomes false the loop never ends (infinite loop).
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 and continue

break leaves the loop completely. continue skips the rest of this round and goes to the next.

Real use: stop searching as soon as you find the item (break).
void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 3) continue;
    if (i == 6) break;
    print(i);
  }
  print('done');
}

for-in and nested loops

for (var x in list) visits every item. A loop inside a loop makes rows and columns.

Think of a clock: the minute hand (inner loop) completes 60 steps for each step of the hour hand (outer loop).
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);
  }
}

Animated explainer: How a for loop runs

Press Next to walk through it step by step, or Auto play.

Animated explainer: if / else if / else ladder

Press Next to walk through it step by step, or Auto play.
EASYReal project: result processingExample 1 of 10

Pass or fail

A simple if / else decides between two outcomes.
void main() {
  int marks = 45;
  if (marks >= 33) {
    print('Congratulations, you passed!');
  } else {
    print('Sorry, try again.');
  }
}
Try it yourself: Try marks = 20.
Change the number.
EASYReal project: numbering rows in a reportExample 2 of 10

Count 1 to 10

A for loop saves you from writing ten print lines.
void main() {
  for (int i = 1; i <= 10; i++) {
    print('Roll no. $i');
  }
}
Try it yourself: Print numbers 10 down to 1.
for (int i = 10; i >= 1; i--)
EASYReal project: maths practice appExample 3 of 10

Multiplication table

Loop counter times a fixed number gives a table.
void main() {
  int n = 7;
  for (int i = 1; i <= 10; i++) {
    print('$n x $i = ${n * i}');
  }
}
Try it yourself: Print the table of 12.
Set n = 12.
EASYReal project: calendar and timetable appExample 4 of 10

Day of the week

switch picks one action from several choices.
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');
  }
}
Try it yourself: Change day to 7 and 3.
Edit the day variable.
EASYReal project: totals in accountsExample 5 of 10

Sum of numbers

A running total is the most common loop pattern: start at 0, add each time.
void main() {
  int total = 0;
  for (int i = 1; i <= 100; i++) {
    total += i;
  }
  print('Sum of 1 to 100 = $total');
}
Try it yourself: Find the sum of even numbers up to 50.
Use i += 2 starting from 2.
MEDIUMReal project: school ERP report cardExample 6 of 10

Grade calculator

An if-else-if ladder converts marks into a grade for each student using a loop.
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');
  });
}
Try it yourself: Add two more students.
Add 'Kiran': 77 to the map.
MEDIUMReal project: searching in dataExample 7 of 10

Find first multiple (break)

break stops the loop when the answer is found, saving time.
void main() {
  for (int i = 100; i < 200; i++) {
    if (i % 17 == 0) {
      print('First multiple of 17 above 100 is $i');
      break;
    }
  }
}
Try it yourself: Find the first multiple of 23 above 500.
Change numbers.
MEDIUMReal project: filtering recordsExample 8 of 10

Skip with continue

continue skips unwanted rounds. Here odd numbers are skipped.
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');
}
Try it yourself: Skip multiples of 3 instead.
Test i % 3 == 0.
HARDReal project: pattern printing and nested loopsExample 9 of 10

Star pyramid

Nested loops: the outer loop is the row; inner builds spaces and stars.
void main() {
  int rows = 5;
  for (int r = 1; r <= rows; r++) {
    String line = ' ' * (rows - r) + '*' * (2 * r - 1);
    print(line);
  }
}
Try it yourself: Print a pyramid with 7 rows.
Set rows = 7.
HARDReal project: security and cryptography basicsExample 10 of 10

Prime numbers finder

A number is prime if no number from 2 up to its square root divides it. Uses a loop inside a loop with break.
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}');
}
Try it yourself: Find primes up to 100.
Change 50 to 100.

Quick quiz

3 questions. Click an answer.
Which loop runs at least once, even if the condition is false?
forwhiledo-whilefor-in
What does break do inside a loop?
Skips one roundLeaves the loopRestarts the loopPauses
Which keyword handles "everything else" in a switch?
elsedefaultotherfinal
Score: 0 / 3

Recap: what you learned in Module 5

if / else

Decide with conditions. First true block runs.

switch

Compare one value against many cases. default for the rest.

for

Repeat a known number of times with a counter.

while

Repeat while a condition is true. do-while runs once first.

break / continue

Leave the loop, or skip to the next round.

Nested loops

Loop inside loop for rows and columns.

Next: Functions - Reusable blocks: parameters, return values, named and optional arguments, arrow functions
MODULE 6 · PART 2

Functions

Reusable blocks: parameters, return values, named and optional arguments, arrow functions
You will learn
  • What a function is and why we use it
  • Parameters and return values
  • Optional and named parameters with defaults
  • Arrow functions and anonymous functions
  • Functions as values (callbacks)
  • Recursion and scope
You will build: a bill function, a grade function and a reusable validator
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
⚙

Where is this used in real apps?

A function is a named recipe. Write the steps once, then use the recipe again and again with different ingredients. This keeps programs short and easy to fix.

Billing

calculateGst(price) is written once and used on every bill.

Validation

isValidPhone(text) is called from many forms.

Games

addScore(points) is called whenever the player wins.

Function Calls
⚙
calculateGst(2000)
= 360.0
⚙
isAdult(17)
= false
⚙
greet('Asha')
= Hello Asha

Define and call

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.

Think: defining is writing the recipe; calling is cooking it.
void greet() {
  print('Namaste!');
}

void main() {
  greet();
  greet();
}

Parameters and return

Parameters are the inputs. return sends a value back to the caller. The return type says what kind of value comes back.

Real use: 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 and named parameters

Optional positional: [int x = 1]. Named: {required String name, int age = 18} called as f(name: 'Asha'). Names make calls easy to read.

Flutter uses named parameters everywhere: 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));
}

Arrow and anonymous functions

A one-expression function can use an arrow =>. A function without a name (anonymous) can be stored in a variable.

Reading: (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 as values

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.

Real use: "when the button is pressed, call this function".
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());
}

Recursion and scope

A function can call itself (recursion): it needs a stopping rule (base case). A variable made inside a function lives only inside it (scope).

Careful: without a base case, recursion never stops and crashes (stack overflow).
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);
}

Animated explainer: The call stack: factorial(3)

Press Next to walk through it step by step, or Auto play.

Animated explainer: Input to output

Press Next to walk through it step by step, or Auto play.
EASYReal project: welcome text in an appExample 1 of 10

Greeting function

One function used many times with different names.
void greet(String name) {
  print('Namaste, $name! Welcome to BrainBit Infotech.');
}

void main() {
  greet('Asha');
  greet('Rohit');
  greet('Meena');
}
Try it yourself: Call greet with your own name.
greet('Your name');
EASYReal project: maths and physics formulasExample 2 of 10

Square and cube

A function with a return value can be used inside print and other calculations.
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));
}
Try it yourself: Write a function that doubles a number.
int twice(int n) => n * 2;
EASYReal project: validating inputExample 3 of 10

Even or odd function

A function that returns bool is called a check or predicate.
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'}');
  }
}
Try it yourself: Write isAdult(int age).
return age >= 18;
EASYReal project: billing softwareExample 4 of 10

GST function

The GST rule is written once. If the rate changes you edit only one line.
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));
}
Try it yourself: Find the total for Rs 4,500 at 28 percent GST.
withGst(4500, 28)
EASYReal project: finding the highest markExample 5 of 10

Maximum of three

Function with three inputs and if statements.
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));
}
Try it yourself: Write smallest(a, b, c).
Use < instead of >.
MEDIUMReal project: building profile cards (Flutter style)Example 6 of 10

Named parameters

Named parameters make calls self-explaining. required forces the caller to give a value.
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));
}
Try it yourself: Add a named parameter called phone.
Add String phone = 'NA' to the braces.
MEDIUMReal project: report card printingExample 7 of 10

Grade function with loop

Small functions are combined: gradeOf is called for every student.
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)}');
  }
}
Try it yourself: Add a new marks value and check its grade.
Add a number to the list.
MEDIUMReal project: button click handlersExample 8 of 10

Callback function

Pass a function into another function. applyTo does not know what the action is; the caller decides.
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);
}
Try it yourself: Use a rule that subtracts 1.
(n) => n - 1
HARDReal project: interview classic and algorithm studyExample 9 of 10

Fibonacci with recursion

A function calling itself. Each number is the sum of the previous two.
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)}');
}
Try it yourself: Print the first 15 numbers.
Change i < 12 to i < 15.
HARDReal project: banking app with reusable functionsExample 10 of 10

Loan EMI toolkit

Three functions work together; each does one job. This is how real projects are structured.
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))}');
  }
}
Try it yourself: Compare 10 and 15 years.
Change the list to [10, 15].

Quick quiz

3 questions. Click an answer.
What does a function with return type void give back?
A numberNothingTexttrue
How do you call a named parameter?
f('Asha')f(name: 'Asha')f[name]f -> name
What must every recursive function have?
A loopA base caseA stringAn import
Score: 0 / 3

Recap: what you learned in Module 6

Function

A named reusable block: write once, call many times.

Parameters

Inputs. return gives back an output.

Optional / named

[x = 1] and {required name} make calls flexible.

Arrow =>

One-expression shortcut.

Callbacks

Pass a function into another function.

Recursion

A function calling itself with a base case.

Next: Lists and Iterables - Store many items: add, remove, sort, map, where, reduce
MODULE 7 · PART 2

Lists and Iterables

Store many items: add, remove, sort, map, where, reduce
You will learn
  • Create lists and read items by index
  • Add, insert, remove and update items
  • Loop over lists and use list properties
  • Sort, reverse and search a list
  • map, where, reduce, fold, any, every
  • Spread, collection if/for and nested lists
You will build: a marks list, a shopping cart and a leaderboard
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📋

Where is this used in real apps?

One variable can hold only one value. A list holds many values in order: all marks of a class, all items in a cart, all contacts in a phone.

Shopping cart

The cart is a list of products. Add, remove and total them.

Contacts

A phone keeps a sorted list of names.

Leaderboard

Scores are sorted from highest to lowest.

My Cart
🍚
Apples 1 kg
Rs 180
🥛
Milk 2 L
Rs 120
🍞
Bread
Rs 45

Create and read a list

A list is written in square brackets. Positions start at 0. first, last, length help.

Tip: 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, insert, remove

add puts an item at the end, insert at a position, remove deletes by value, removeAt by position.

Real use: add to cart, remove from cart.
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);
}

Looping and properties

Use for-in, forEach or index loops. isEmpty, contains, indexOf answer questions.

Remember: index 0 is the first item; the last index is length - 1.
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, reverse, sublist

sort() sorts in place. Give it a rule for custom order. reversed flips. sublist cuts a part.

Real use: leaderboard: highest score first.
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, where, reduce

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.

Real use: 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));
}

Spread, collection if/for, nested

... spreads one list into another. Inside a list literal you can use if and for. A list can hold lists (a table).

Flutter uses this a lot to build screens from lists.
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]);
}

Animated explainer: A list is a row of numbered boxes

Press Next to walk through it step by step, or Auto play.

Animated explainer: map then where then fold

Press Next to walk through it step by step, or Auto play.
EASYReal project: class marks sheetExample 1 of 10

Marks list

A list stores all marks together; loops and properties give the facts.
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]}');
}
Try it yourself: Add your own marks and print the count.
Add numbers to the list.
EASYReal project: grocery appExample 2 of 10

Shopping list

add, remove and contains are the basic list actions.
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')}');
}
Try it yourself: Add Sugar and remove Salt.
Use add and remove.
EASYReal project: accounts and marksExample 3 of 10

Total and average

Loop and add each item: a running total.
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}');
}
Try it yourself: Add the weekend sales and recalculate.
Add two more numbers.
EASYReal project: finding top and lowest scoreExample 4 of 10

Biggest and smallest

Sort a copy and read its ends.
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');
}
Try it yourself: Find the second highest score.
sorted[sorted.length - 2]
EASYReal project: undo history, newest firstExample 5 of 10

Reverse a list

reversed gives the items backwards.
void main() {
  var steps = ['Open', 'Edit', 'Save', 'Close'];
  print(steps.reversed.toList());
  for (var s in steps.reversed) {
    print(s);
  }
}
Try it yourself: Print your name's letters reversed.
'Asha'.split('').reversed.join()
MEDIUMReal project: game and quiz appExample 6 of 10

Leaderboard

Sort list of scores descending and print rank.
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]}');
  }
}
Try it yourself: Add a fifth player.
Add to both lists.
MEDIUMReal project: price filter on an e-commerce pageExample 7 of 10

Filter expensive items

where filters; map reshapes; toList finishes the chain.
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)}');
}
Try it yourself: Show only prices below 300.
Use p < 300.
MEDIUMReal project: cleaning contact listsExample 8 of 10

Remove duplicates

A Set keeps only unique values. Convert back to a list.
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}');
}
Try it yourself: Clean a list of city names with repeats.
Make your own list.
HARDReal project: shopping cart total with foldExample 9 of 10

Cart with quantities

Two parallel lists drive a total using fold and a generated index list.
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)}');
}
Try it yourself: Add a fourth item with quantity 4.
Add to all three lists.
HARDReal project: tables, spreadsheets and image dataExample 10 of 10

Matrix and transpose

A list of lists is a table. Transposing swaps rows and columns.
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');
}
Try it yourself: Add a third row to the matrix.
Add [7, 8, 9] to m.

Quick quiz

3 questions. Click an answer.
What is the first index of a list?
10-1first
Which method keeps only items that pass a test?
mapwherefoldadd
What does [...a, 3] do?
Deletes aSpreads a then adds 3Prints aSorts a
Score: 0 / 3

Recap: what you learned in Module 7

List

Ordered items in [ ]. Index starts at 0.

Change

add, insert, remove, removeAt, [i] = value.

Loop

for-in and forEach visit each item.

Sort

sort(), reversed, sublist.

Transform

map, where, fold, reduce, any, every.

Build

Spread ..., collection if and for, nested lists.

Next: Maps and Sets - Key-value data and unique collections, plus JSON-like records
MODULE 8 · PART 2

Maps and Sets

Key-value data and unique collections, plus JSON-like records
You will learn
  • Create a Map of key-value pairs
  • Read, add, update and remove entries
  • Loop over keys, values and entries
  • Sets: unique values and set maths
  • Maps of lists and lists of maps (JSON-like data)
  • Choosing List, Map or Set
You will build: a phone book, a word counter and a student database
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📑

Where is this used in real apps?

A list finds things by position. A map finds things by name: look up "Asha" and get her phone number. A set keeps every value only once.

Phone book

Name is the key, number is the value.

Student database

Each student record is a map: name, roll, marks.

API data (JSON)

Servers send data as maps and lists. Apps read them.

Phone Book
📞
Asha
98001 11111
📞
Rohit
98002 22222
📞
Meena
98003 33333

Create a map

A map stores key: value pairs in curly brackets. Keys are unique. Look up with map[key]. A missing key gives null.

Compare: a list uses numbers (0, 1, 2) to find items; a map uses your own keys.
void main() {
  Map<String, String> phone = {
    'Asha': '98001',
    'Rohit': '98002',
  };
  print(phone['Asha']);
  print(phone['Zoya']);
  print(phone.length);
  print(phone);
}

Change a map

map[key] = value adds or updates. remove(key) deletes. containsKey checks. putIfAbsent adds only when missing.

Real use: stock counts that change with every sale.
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);
}

Loop over a map

keys, values and entries can be looped. forEach gives key and value together.

Tip: maps remember the order you added items in.
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}');
  }
}

Sets

A Set keeps unique values and ignores duplicates. Use union, intersection and difference to compare two sets.

Real use: "students who joined both Dart and Flutter courses" = intersection.
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));
}

Maps of lists and lists of maps

Data from the internet (JSON) is built from maps and lists. A list of maps is a table where every map is a row.

Next modules turn these maps into proper classes. For now this is the quick way.
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);
}

List, Map or Set?

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."

List

Order matters, duplicates allowed. Cart items, marks.

Map

Look up by key. Phone book, settings, JSON.

Set

Unique values and fast contains. Tags, visited pages.

Rule of thumb: start with a List; use a Map when you keep searching by name.

Animated explainer: Map: look up by key

Press Next to walk through it step by step, or Auto play.

Animated explainer: Set union, intersection, difference

Press Next to walk through it step by step, or Auto play.
EASYReal project: contacts appExample 1 of 10

Phone book

A map from name to number; lookup is instant.
void main() {
  var phone = {'Asha': '98001', 'Rohit': '98002', 'Meena': '98003'};
  print(phone['Rohit']);
  phone['Sonu'] = '98004';
  print(phone.length);
  print(phone);
}
Try it yourself: Add your own number.
phone['You'] = '99999';
EASYReal project: inventory managementExample 2 of 10

Update stock

Reading, updating and removing keys are the daily map actions.
void main() {
  var stock = {'rice': 50, 'dal': 30, 'oil': 20};
  stock['rice'] = stock['rice']! - 8;
  stock['dal'] = 0;
  stock.remove('oil');
  print(stock);
}
Try it yourself: Sell 5 units of dal (set the new value).
stock['dal'] = ...
EASYReal project: report generationExample 3 of 10

Print all entries

forEach walks over every key and value.
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)}');
}
Try it yourself: Add one more course.
Add a new key.
EASYReal project: removing duplicatesExample 4 of 10

Unique values

Sets drop duplicates automatically.
void main() {
  var visits = ['Ranchi', 'Patna', 'Ranchi', 'Gaya', 'Patna'];
  var cities = visits.toSet();
  print(cities);
  print('Unique cities: ${cities.length}');
}
Try it yourself: Count unique letters in 'banana'.
'banana'.split('').toSet()
EASYReal project: login and settings lookupsExample 5 of 10

Key check

containsKey prevents errors from missing data.
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'));
}
Try it yourself: Check the user 'meena'.
Change name.
MEDIUMReal project: text analysis and trending wordsExample 6 of 10

Word counter

Count how many times each word appears using a map.
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}'));
}
Try it yourself: Count letters in a word instead.
Use split('').
MEDIUMReal project: school databaseExample 7 of 10

Student records

A list of maps is a table. Filter and calculate across rows.
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');
}
Try it yourself: Show only class 9 students.
Filter on s['class'] == 9.
MEDIUMReal project: course enrolment analysisExample 8 of 10

Common students

Set operations answer real questions quickly.
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}');
}
Try it yourself: Add a third set for Java students.
var java = {...};
HARDReal project: reports grouped by categoryExample 9 of 10

Group by city

Build a map of lists: each key holds a list of names. Grouping is a classic data task.
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(', ')}');
  });
}
Try it yourself: Add two more people.
Add pairs to the list.
HARDReal project: shop management appExample 10 of 10

Mini inventory with low-stock alert

Combine map updates, loops and conditions in one small system.
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)}');
}
Try it yourself: Add a sale that makes Dal low.
Add ['Dal', 5] to sales.

Quick quiz

3 questions. Click an answer.
What does a map return for a key that does not exist?
0nullAn empty stringIt crashes
Which collection keeps only unique values?
ListMapSetString
How do you add or update a key in a map?
map.add(k, v)map[k] = vmap.push(k)map(k, v)
Score: 0 / 3

Recap: what you learned in Module 8

Map

Key: value pairs. Look up with map[key].

Change

map[k] = v, remove, containsKey, putIfAbsent.

Loop

keys, values, entries, forEach.

Set

Unique values. union, intersection, difference.

Nested data

Lists of maps look like JSON from servers.

Choose

List by position, Map by key, Set for uniqueness.

Next: the next part of the course.

Dart Code Lab - write any Dart program (Ctrl+Enter to run)