DART PROGRAMMING COURSE · BRAINBIT INFOTECH

Part 4
Advanced Dart, Errors and Async

Module 13: Generics, Extensions and Operators

Reusable type-safe code, add methods to existing types, custom operators · 6 h

Module 14: Errors and Exceptions

try, catch, finally, throw, custom exceptions and defensive programming · 6 h

Module 15: Asynchronous Dart: Future, async and await

Do slow work without freezing: Future, async/await, timers, parallel tasks · 7 h

Module 16: Streams, Generators and Timers

Many values over time: Stream, listen, async*, sync*, StreamController, Timer · 6 h

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

MODULE 13 · PART 4

Generics, Extensions and Operators

Reusable type-safe code, add methods to existing types, custom operators
You will learn
  • Generics: List<T> and your own Box<T>
  • Generic functions and bounds (T extends num)
  • Extension methods on String, int and List
  • Operator overloading: +, -, ==, []
  • Callable classes, typedef and getters
  • Putting them together: a small Money and Stack
You will build: a generic Box, a Stack, a money type with + and extension helpers
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧰

Where is this used in real apps?

Generics let one class or function work with any type safely. Extensions add new abilities to types you did not write. Operators make your own classes feel natural: money1 + money2.

Collections

List, Map are generics you already use.

Helper methods

'9876543210'.isValidPhone is an extension you write once.

Maths types

Money, Fraction and Vector use + - * operators.

Type-safe Box
📦
Box<int> holds 42
safe
📦
Box<String> holds Ranchi
safe
🚧
Box<int> holds text
blocked

Generic class

class Box<T> works for any type T. When you make Box<int>, T becomes int everywhere. Dart then stops you from putting text inside.

Think: T is a blank to be filled with a type when the object is built.
class Box<T> {
  T value;
  Box(this.value);
  T get() => value;
  void set(T v) => value = v;
}

void main() {
  var a = Box<int>(42);
  var b = Box<String>('Ranchi');
  print(a.get() + 1);
  print(b.get().toUpperCase());
  a.set(100);
  print(a.value);
}

Generic functions and bounds

Functions can be generic too. A bound restricts T: T extends num allows only int and double, so you may use maths inside.

Real use: one biggest works for ints, doubles and prices.
T firstOf<T>(List<T> items) => items.first;

T biggest<T extends num>(T a, T b) => a > b ? a : b;

double sumAll<T extends num>(List<T> xs) {
  double s = 0;
  for (var x in xs) {
    s += x;
  }
  return s;
}

void main() {
  print(firstOf(['a', 'b']));
  print(firstOf([3, 4]));
  print(biggest(7, 3));
  print(biggest(2.5, 9.5));
  print(sumAll([1, 2, 3]));
}

Extension methods

extension Name on Type { ... } adds methods to a type you cannot edit, such as String or int. Then call them with a dot like built-in ones.

Real use: a project collects such helpers in one utils file.
extension StringTools on String {
  String get title => isEmpty ? this : this[0].toUpperCase() + substring(1);
  bool get isPhone => length == 10 && int.tryParse(this) != null;
}
extension IntTools on int {
  bool get isPrime {
    if (this < 2) return false;
    for (int i = 2; i * i <= this; i++) {
      if (this % i == 0) return false;
    }
    return true;
  }
}
void main() {
  print('ranchi'.title);
  print('9876543210'.isPhone);
  print('12345'.isPhone);
  print(13.isPrime);
  print(15.isPrime);
}

Operator overloading

Define operator +, operator -, operator ==, operator [] to teach your class what the symbols mean.

Why paise? Storing money as whole paise avoids decimal rounding errors.
class Money {
  final int paise;
  Money(this.paise);
  Money operator +(Money o) => Money(paise + o.paise);
  Money operator -(Money o) => Money(paise - o.paise);
  Money operator *(int n) => Money(paise * n);
  bool operator >(Money o) => paise > o.paise;
  @override
  String toString() => 'Rs ${(paise / 100).toStringAsFixed(2)}';
}
void main() {
  var a = Money(1550);
  var b = Money(2575);
  print(a + b);
  print(b - a);
  print(a * 3);
  print(b > a);
}

typedef, callable class, getters

typedef gives a short name to a function type. A class with a call method can be used like a function.

Reading: triple(14) secretly runs triple.call(14).
typedef Rule = bool Function(int);

class Multiplier {
  final int by;
  Multiplier(this.by);
  int call(int x) => x * by;
}

List<int> pick(List<int> v, Rule r) => v.where(r).toList();

void main() {
  var triple = Multiplier(3);
  print(triple(14));
  print(pick([1, 2, 3, 4, 5, 6], (n) => n.isEven));
  Rule big = (n) => n > 10;
  print(big(50));
}

Generic Stack

A stack is last-in, first-out like a pile of plates. Written once with a generic, it works for any type.

Real use: the Back button of an app is a stack of screens.
class Stack<T> {
  final List<T> _items = [];
  void push(T x) => _items.add(x);
  T pop() => _items.removeLast();
  T get top => _items.last;
  bool get isEmpty => _items.isEmpty;
  int get size => _items.length;
}

void main() {
  var s = Stack<String>();
  s.push('Home');
  s.push('Courses');
  s.push('Dart');
  print(s.top);
  print(s.pop());
  print(s.size);
}

Animated explainer: Generic Box<T>

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

Animated explainer: Stack: last in, first out

Press Next to walk through it step by step, or Auto play.
EASYReal project: wrapping any value safelyExample 1 of 10

Generic Box

One class, different types. Dart checks the type for you.
class Box<T> {
  T value;
  Box(this.value);
  @override
  String toString() => 'Box($value)';
}

void main() {
  print(Box<int>(7));
  print(Box<String>('Namaste'));
  print(Box<double>(2.5));
  print(Box<List<int>>([1, 2, 3]));
}
Try it yourself: Make a Box.
Box(true)
EASYReal project: cleaning text for displayExample 2 of 10

Capitalise extension

An extension adds title to every String.
extension Cap on String {
  String get title => split(' ').map((w) => w.isEmpty ? w : w[0].toUpperCase() + w.substring(1)).join(' ');
}

void main() {
  print('welcome to ranchi'.title);
  print('asha kumari'.title);
}
Try it yourself: Add a getter that counts words.
int get words => split(' ').length;
EASYReal project: readable maths codeExample 3 of 10

Even and odd extension

Extension on int: 7.isOddNumber reads like English.
extension NumberTools on int {
  bool get isOddNumber => this % 2 != 0;
  int get squared => this * this;
  String get inRupees => 'Rs $this';
}

void main() {
  print(7.isOddNumber);
  print(9.squared);
  print(2500.inRupees);
}
Try it yourself: Add a cubed getter.
int get cubed => this * this * this;
EASYReal project: sorting algorithmsExample 4 of 10

Generic swap

A generic function swaps any two values in a list.
void swap<T>(List<T> a, int i, int j) {
  T temp = a[i];
  a[i] = a[j];
  a[j] = temp;
}

void main() {
  var nums = [1, 2, 3];
  swap(nums, 0, 2);
  print(nums);
  var names = ['Asha', 'Rohit'];
  swap(names, 0, 1);
  print(names);
}
Try it yourself: Swap positions 1 and 2 of a list of 3 cities.
swap(cities, 1, 2);
EASYReal project: maths and game developmentExample 5 of 10

Vector operators

Operator + joins two vectors with natural code.
class Vec {
  final double x, y;
  Vec(this.x, this.y);
  Vec operator +(Vec o) => Vec(x + o.x, y + o.y);
  Vec operator -(Vec o) => Vec(x - o.x, y - o.y);
  @override
  String toString() => '($x, $y)';
}

void main() {
  var a = Vec(1, 2);
  var b = Vec(3, 4);
  print(a + b);
  print(b - a);
}
Try it yourself: Add a * operator for scaling.
Vec operator *(double k) => Vec(x * k, y * k);
MEDIUMReal project: billing systems that avoid rounding errorsExample 6 of 10

Money type

Store paise as an int, format as rupees. Operators make bills readable.
class Money {
  final int paise;
  Money(this.paise);
  Money.rs(double r) : paise = (r * 100).round();
  Money operator +(Money o) => Money(paise + o.paise);
  Money operator *(int n) => Money(paise * n);
  @override
  String toString() => 'Rs ${(paise ~/ 100)}.${(paise % 100).toString().padLeft(2, '0')}';
}

void main() {
  var pen = Money.rs(12.50);
  var book = Money.rs(149.75);
  var bill = pen * 4 + book * 2;
  print(bill);
  print(Money.rs(0.1) + Money.rs(0.2));
}
Try it yourself: Add a discount operator -.
Money operator -(Money o) => ...
MEDIUMReal project: undo in editors, back in appsExample 7 of 10

Generic Stack for undo

A stack remembers actions; pop undoes the latest.
class Stack<T> {
  final List<T> _items = [];
  void push(T x) => _items.add(x);
  T pop() => _items.removeLast();
  bool get isEmpty => _items.isEmpty;
}

void main() {
  var history = Stack<String>();
  for (var a in ['type A', 'type B', 'delete B', 'type C']) {
    history.push(a);
  }
  while (!history.isEmpty) {
    print('Undo: ${history.pop()}');
  }
}
Try it yourself: Use a Stack to reverse the list [1,2,3].
Push all, then pop all.
MEDIUMReal project: maths helpers for ints and doublesExample 8 of 10

Bounded generic

T extends num lets one function handle ints and doubles.
T maxOf<T extends num>(List<T> xs) {
  T best = xs.first;
  for (var x in xs) {
    if (x > best) best = x;
  }
  return best;
}

double average<T extends num>(List<T> xs) => xs.fold(0.0, (a, b) => a + b) / xs.length;

void main() {
  print(maxOf([3, 9, 4]));
  print(maxOf([2.5, 1.5]));
  print(average([70, 80, 90]));
  print(average([1.5, 2.5]));
}
Try it yourself: Write minOf.
Use < instead of >.
HARDReal project: token and helpdesk systemsExample 9 of 10

Generic Queue for tickets

A queue is first-in, first-out. A generic class serves any ticket type.
class Queue2<T> {
  final List<T> _items = [];
  void add(T x) => _items.add(x);
  T next() => _items.removeAt(0);
  int get waiting => _items.length;
  bool get isEmpty => _items.isEmpty;
}
class Ticket {
  final int no;
  final String name;
  Ticket(this.no, this.name);
}
void main() {
  var q = Queue2<Ticket>();
  q.add(Ticket(1, 'Asha'));
  q.add(Ticket(2, 'Rohit'));
  q.add(Ticket(3, 'Meena'));
  while (!q.isEmpty) {
    var t = q.next();
    print('Now serving #${t.no} ${t.name} (waiting: ${q.waiting})');
  }
}
Try it yourself: Add a peek method.
T get first => _items.first;
HARDReal project: maths and teaching softwareExample 10 of 10

Fraction class

Operators, == and a helper function work together to make a complete type.
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);

class Fraction {
  final int n, d;
  Fraction(int a, int b) : n = a ~/ gcd(a, b), d = b ~/ gcd(a, b);
  Fraction operator +(Fraction o) => Fraction(n * o.d + o.n * d, d * o.d);
  Fraction operator *(Fraction o) => Fraction(n * o.n, d * o.d);
  @override
  bool operator ==(Object o) => o is Fraction && o.n == n && o.d == d;
  @override
  int get hashCode => n * 31 + d;
  @override
  String toString() => '$n/$d';
}

void main() {
  var a = Fraction(1, 2);
  var b = Fraction(1, 3);
  print(a + b);
  print(a * b);
  print(Fraction(2, 4) == a);
}
Try it yourself: Add subtraction.
Fraction operator -(Fraction o) => ...

Quick quiz

3 questions. Click an answer.
What does T mean in Box<T>?
A fixed typeA placeholder type filled in laterA textA number
What does an extension do?
Adds methods to an existing typeDeletes a classMakes a loopImports a file
Which keyword defines what + does for your class?
override +operator +plus()add +
Score: 0 / 3

Recap: what you learned in Module 13

Generics

Box, List: one code, many safe types.

Bounds

T extends num limits types and unlocks maths.

Extensions

Add methods to existing types.

Operators

operator + - * == [] for your classes.

call / typedef

Callable objects and short function-type names.

Stack / Queue

Generic LIFO and FIFO structures.

Next: Errors and Exceptions - try, catch, finally, throw, custom exceptions and defensive programming
MODULE 14 · PART 4

Errors and Exceptions

try, catch, finally, throw, custom exceptions and defensive programming
You will learn
  • Kinds of errors: syntax, runtime and logic
  • try / catch / finally
  • Catching specific exceptions with on
  • throw and custom exception classes
  • rethrow, assert and validation
  • Designing code that fails safely
You will build: a safe calculator, a login checker and a payment that never loses money on error
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🚨

Where is this used in real apps?

Real apps meet bad input, missing files and weak internet. An exception is Dart saying "something went wrong". With try and catch your app handles the problem calmly instead of crashing.

Payments

If the bank is down, show a message and do not charge twice.

Forms

Catch bad numbers typed by a user.

Network apps

Handle timeout, no internet, wrong data.

Pay Now
⚠
Payment failed
caught & shown
🔄
Try again
retry
✅
Order saved
safe

Three kinds of errors

Syntax error: the code breaks grammar rules (Dart stops before running). Runtime error: crashes while running (divide by zero in some types, bad parse). Logic error: runs but gives the wrong answer (you wrote + instead of *).

Syntax

Missing semicolon or bracket. The editor shows a red line.

Runtime

int.parse('abc') throws FormatException while running.

Logic

Total = price + qty instead of price * qty. No crash, wrong bill!

Logic errors are the hardest to find: test with known answers.

try, catch, finally

Put risky code in try. If it throws, Dart jumps to catch. finally always runs, success or failure: perfect for cleanup.

Without try the program would stop at the bad line.
void main() {
  try {
    int n = int.parse('abc');
    print(n);
  } catch (e) {
    print('Caught a ${e.runtimeType}');
  } finally {
    print('This line always runs');
  }
  print('Program continues');
}

Catch specific exceptions with on

on FormatException catch (e) handles only that type. Add several on blocks for different problems, and a plain catch last for the rest.

Order: specific handlers first, general catch last.
void main() {
  for (var input in ['42', 'abc', '0']) {
    try {
      int n = int.parse(input);
      if (n == 0) throw ArgumentError('zero');
      print(100 ~/ n);
    } on FormatException {
      print('"$input" is not a number');
    } on ArgumentError {
      print('Cannot divide by zero');
    } catch (e) {
      print('Other problem: $e');
    }
  }
}

throw and custom exceptions

throw raises an exception yourself. Make your own class that implements Exception to give clear, meaningful names to problems.

Real use: InvalidOtp, UserNotFound, NetworkTimeout each have their own class.
class InsufficientFunds implements Exception {
  final double needed;
  InsufficientFunds(this.needed);
  @override
  String toString() => 'Short by Rs $needed';
}
double withdraw(double balance, double amt) {
  if (amt > balance) throw InsufficientFunds(amt - balance);
  return balance - amt;
}
void main() {
  try {
    print(withdraw(1000, 300));
    print(withdraw(1000, 1500));
  } on InsufficientFunds catch (e) {
    print('Failed: $e');
  }
}

rethrow, assert, StackTrace

rethrow passes an error on after you log it. assert(condition, message) checks assumptions while developing.

Note: assert is checked in debug mode only, not in released apps.
void load() {
  try {
    throw FormatException('bad data');
  } catch (e) {
    print('Logging: $e');
    rethrow;
  }
}

void main() {
  try {
    load();
  } catch (e) {
    print('Main handled: $e');
  }
  int age = 20;
  assert(age > 0, 'Age must be positive');
  print('assert passed');
}

Failing safely: validate early

Check input before work starts. Return a clear message. Keep try blocks small. Never leave a catch empty: at least print or log the problem.

tryParse returns null instead of throwing: often neater than try/catch.
int? safeParse(String s) => int.tryParse(s.trim());

String divide(String a, String b) {
  var x = safeParse(a), y = safeParse(b);
  if (x == null || y == null) return 'Please enter whole numbers';
  if (y == 0) return 'Cannot divide by zero';
  return '${x / y}';
}

void main() {
  print(divide('10', '4'));
  print(divide('10', '0'));
  print(divide('ten', '2'));
}

Animated explainer: try / catch / finally flow

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

Animated explainer: An exception travels up

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

Catch a bad number

The program does not crash; it shows a friendly message.
void main() {
  try {
    int age = int.parse('twenty');
    print(age);
  } catch (e) {
    print('Please type digits only');
  }
  print('Form still works');
}
Try it yourself: Try parsing '25' instead.
Change the text.
EASYReal project: closing files and connectionsExample 2 of 10

Finally always runs

Cleanup code goes in finally.
void main() {
  print('Opening file');
  try {
    print('Reading...');
    throw Exception('Disk error');
  } catch (e) {
    print('Error: $e');
  } finally {
    print('Closing file');
  }
}
Try it yourself: Remove the throw and see what happens.
Delete the throw line.
EASYReal project: safe reading of user numbersExample 3 of 10

tryParse

int.tryParse returns null instead of throwing.
void main() {
  for (var t in ['12', 'x9', '', '7.5', ' 40 ']) {
    int? n = int.tryParse(t.trim());
    print('"$t" -> ${n ?? 'invalid'}');
  }
}
Try it yourself: Use double.tryParse.
double.tryParse(t)
EASYReal project: validation rulesExample 4 of 10

Throw your own error

throw stops the function when a rule breaks.
void setAge(int age) {
  if (age < 0 || age > 120) {
    throw ArgumentError('Age $age is not realistic');
  }
  print('Age saved: $age');
}

void main() {
  setAge(25);
  try {
    setAge(300);
  } catch (e) {
    print(e);
  }
}
Try it yourself: Reject ages below 5.
Change the condition.
EASYReal project: calculator appsExample 5 of 10

Safe divide

Check first, calculate after. Prevents the crash entirely.
double? safeDivide(num a, num b) {
  if (b == 0) return null;
  return a / b;
}

void main() {
  print(safeDivide(10, 4));
  print(safeDivide(5, 0));
  print(safeDivide(9, 3) ?? 'error');
}
Try it yourself: Add safeSqrt for negative numbers.
Return null for negatives.
MEDIUMReal project: robust input handlingExample 6 of 10

Several handlers

Different problems get different messages using on.
void process(String a, String b) {
  try {
    int x = int.parse(a);
    int y = int.parse(b);
    if (y == 0) throw ArgumentError('zero');
    print('$x / $y = ${x ~/ y}');
  } on FormatException {
    print('Not a number');
  } on ArgumentError {
    print('Cannot divide by zero');
  }
}

void main() {
  process('20', '4');
  process('20', 'x');
  process('20', '0');
}
Try it yourself: Handle a RangeError too.
Add an on RangeError block.
MEDIUMReal project: banking and walletsExample 7 of 10

Custom exception

A named exception makes the error easy to handle and easy to understand.
class LowBalance implements Exception {
  final double shortBy;
  LowBalance(this.shortBy);
  @override
  String toString() => 'LowBalance: add Rs $shortBy more';
}
double pay(double wallet, double bill) {
  if (bill > wallet) throw LowBalance(bill - wallet);
  return wallet - bill;
}
void main() {
  double wallet = 500;
  for (var bill in [120.0, 300.0, 200.0]) {
    try {
      wallet = pay(wallet, bill);
      print('Paid $bill, left $wallet');
    } on LowBalance catch (e) {
      print(e);
    }
  }
}
Try it yourself: Add a bill of Rs 50.
Add 50.0 to the list.
MEDIUMReal project: security and login screensExample 8 of 10

Login with attempts

Track failed attempts; lock after three. Exceptions carry the reason.
class WrongPassword implements Exception {}
class Locked implements Exception {}
int attempts = 0;
void login(String pw) {
  if (attempts >= 3) throw Locked();
  if (pw != 'dart123') {
    attempts++;
    throw WrongPassword();
  }
  print('Welcome!');
}
void main() {
  for (var p in ['abc', 'xyz', 'dart123', 'q', 'w']) {
    try {
      login(p);
    } on WrongPassword {
      print('Wrong password ($attempts/3)');
    } on Locked {
      print('Account locked');
    }
  }
}
Try it yourself: Allow only 2 attempts.
Change 3 to 2.
HARDReal project: unreliable network callsExample 9 of 10

Retry with attempts

A loop retries up to three times and then gives up cleanly. Real apps do this for weak mobile networks.
int calls = 0;
String fetch() {
  calls++;
  if (calls < 3) throw Exception('Network down (call $calls)');
  return 'Data received';
}
String fetchWithRetry(int max) {
  for (int i = 1; i <= max; i++) {
    try {
      return fetch();
    } catch (e) {
      print('Attempt $i failed: $e');
    }
  }
  return 'Gave up after $max attempts';
}
void main() {
  print(fetchWithRetry(5));
  calls = -10;
  print(fetchWithRetry(2));
}
Try it yourself: Allow 3 attempts only in the second call.
Change 2 to 3.
HARDReal project: bank transfers and ordersExample 10 of 10

Transaction rollback

If anything fails midway, undo what was done so no money is lost. The finally block reports the outcome.
class Account {
  double balance;
  Account(this.balance);
}
void transfer(Account from, Account to, double amt) {
  double fromBefore = from.balance, toBefore = to.balance;
  try {
    from.balance -= amt;
    if (from.balance < 0) throw Exception('Insufficient funds');
    to.balance += amt;
    print('Transferred Rs $amt');
  } catch (e) {
    from.balance = fromBefore;
    to.balance = toBefore;
    print('Rolled back: $e');
  } finally {
    print('A: ${from.balance}  B: ${to.balance}');
  }
}
void main() {
  var a = Account(1000), b = Account(200);
  transfer(a, b, 400);
  transfer(a, b, 900);
}
Try it yourself: Transfer exactly the full balance.
transfer(a, b, 600);

Quick quiz

3 questions. Click an answer.
Which block always runs?
trycatchfinallyon
What does throw do?
Prints textRaises an exceptionEnds the appImports a file
What does int.tryParse('abc') return?
0An exceptionnull-1
Score: 0 / 3

Recap: what you learned in Module 14

Error kinds

Syntax, runtime and logic errors.

try / catch

Handle problems without crashing; finally always runs.

on Type

Handle specific exceptions separately.

throw

Raise your own errors; custom classes implement Exception.

rethrow / assert

Log then pass on; check assumptions in debug mode.

Fail safely

Validate early; tryParse; never an empty catch.

Next: Asynchronous Dart: Future, async and await - Do slow work without freezing: Future, async/await, timers, parallel tasks
MODULE 15 · PART 4

Asynchronous Dart: Future, async and await

Do slow work without freezing: Future, async/await, timers, parallel tasks
You will learn
  • Why apps must not wait: synchronous vs asynchronous
  • Future: a promise of a value later
  • async and await
  • Errors in async code and timeout
  • Future.wait: run tasks together
  • The event loop and execution order
You will build: a fake server call, a loading screen sequence and parallel downloads
7 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
⏱

Where is this used in real apps?

Fetching data from a server can take seconds. If the app waited without doing anything else, the screen would freeze. Async code starts the slow job, keeps the app alive and continues when the answer arrives.

Network apps

Load courses from a server while a spinner is shown.

Files and databases

Read a big file without freezing the screen.

Payments

Wait for the bank reply, then show success.

Loading...
⏳
Fetching courses
await
✅
Got 12 courses
done
🔄
Pull to refresh
async

Future and then

A Future is a promise: "I will give you a value later". Future.delayed pretends to be slow (like a server). .then() runs when the value is ready.

Notice: the last line runs first. The program did not wait. (Delays on slides are shortened 10 times.)
Future<String> fetchName() {
  return Future.delayed(Duration(seconds: 1), () => 'Asha');
}

void main() {
  print('Start');
  fetchName().then((n) => print('Got $n'));
  print('This prints BEFORE the name');
}

async and await

Mark a function async to use await inside. await pauses only this function until the Future completes, then continues on the next line. Code reads top to bottom, like normal code.

Rule: a function that uses await must be async and return a Future.
Future<int> fetchMarks() async {
  await Future.delayed(Duration(seconds: 1));
  return 87;
}

Future<void> main() async {
  print('Loading marks...');
  int m = await fetchMarks();
  print('Marks: $m');
  print('Done');
}

Errors and timeout

Use try/catch around await. .timeout() fails a Future that takes too long. TimeoutException needs import 'dart:async'.

Real use: "Network error, please retry".
import 'dart:async';
Future<String> slowServer() async {
  await Future.delayed(Duration(seconds: 5));
  return 'late reply';
}
Future<String> brokenServer() async {
  await Future.delayed(Duration(milliseconds: 200));
  throw Exception('Server error 500');
}
Future<void> main() async {
  try {
    await brokenServer();
  } catch (e) {
    print('Caught: $e');
  }
  try {
    await slowServer().timeout(Duration(seconds: 1));
  } on TimeoutException {
    print('Too slow, giving up');
  }
}

Future.wait: parallel work

Start many Futures at once and wait for all. Total time is the slowest one, not the sum.

Real use: a home screen loads banners, profile and courses together.
Future<String> download(String f, int sec) async {
  await Future.delayed(Duration(seconds: sec));
  return '$f done';
}

Future<void> main() async {
  var sw = Stopwatch()..start();
  var results = await Future.wait([
    download('video', 3),
    download('image', 1),
    download('notes', 2),
  ]);
  print(results);
  print('Took about 3 sec, not 6');
}

Sequential vs parallel

Awaiting one after another adds the times. Starting first and awaiting later runs them together.

Tip: start independent Futures first, await them after.
Future<int> job(int n) async {
  await Future.delayed(Duration(seconds: 1));
  return n * 10;
}

Future<void> main() async {
  var a = await job(1);
  var b = await job(2);
  print('Sequential: ${a + b} (2 sec)');
  var fa = job(3);
  var fb = job(4);
  print('Parallel  : ${await fa + await fb} (1 sec)');
}

Event loop order

Dart runs normal code first. Then microtasks (scheduleMicrotask, Future.value). Then events like timers (Future.delayed, Timer).

Order: main code, then microtasks, then timer/events.
import 'dart:async';

void main() {
  print('1 main starts');
  Future(() => print('4 event queue'));
  scheduleMicrotask(() => print('3 microtask'));
  Future.delayed(Duration.zero, () => print('5 delayed'));
  print('2 main ends');
}

Animated explainer: Sync blocks, async keeps going

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

Animated explainer: Event loop: who runs first?

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

Fake server call

The program does not freeze; it prints Waiting first, then the result.
Future<String> getCourse() async {
  await Future.delayed(Duration(seconds: 1));
  return 'Dart for Beginners';
}

Future<void> main() async {
  print('Waiting...');
  String c = await getCourse();
  print('Course: $c');
}
Try it yourself: Change the course name.
Change the returned text.
EASYReal project: older style callbacksExample 2 of 10

then callback

then runs code when the value arrives; the next line runs immediately.
void main() {
  Future.delayed(Duration(seconds: 1), () => 42).then((v) {
    print('Value arrived: $v');
  });
  print('Not blocked');
}
Try it yourself: Add a second then that doubles the value.
.then((v) => v * 2)
EASYReal project: OTP timer and exam timersExample 3 of 10

Countdown

A loop with await makes a timer. Each step waits one second.
Future<void> main() async {
  for (int i = 3; i >= 1; i--) {
    print('$i...');
    await Future.delayed(Duration(seconds: 1));
  }
  print('Go!');
}
Try it yourself: Count down from 5.
Change i = 3 to i = 5.
EASYReal project: calculating in the backgroundExample 4 of 10

Async return value

An async function returns a Future; await gets the value out.
Future<int> square(int n) async {
  await Future.delayed(Duration(milliseconds: 300));
  return n * n;
}

Future<void> main() async {
  print(await square(9));
  int total = await square(3) + await square(4);
  print(total);
}
Try it yourself: Add a cube function.
return n * n * n;
EASYReal project: splash and loader screensExample 5 of 10

Loading then result

Typical app pattern: show loading, wait, show data.
Future<List<String>> loadCourses() async {
  await Future.delayed(Duration(seconds: 1));
  return ['Dart', 'Flutter', 'Python'];
}

Future<void> main() async {
  print('Loading...');
  var list = await loadCourses();
  print('Loaded ${list.length} courses:');
  for (var c in list) {
    print(' - $c');
  }
}
Try it yourself: Add a fourth course.
Add to the list.
MEDIUMReal project: handling failed requestsExample 6 of 10

Error from server

try/catch works with await exactly like normal code.
Future<String> login(String user, String pw) async {
  await Future.delayed(Duration(milliseconds: 300));
  if (pw != 'dart123') throw Exception('Wrong password');
  return 'Welcome $user';
}

Future<void> main() async {
  for (var pw in ['abc', 'dart123']) {
    try {
      print(await login('Asha', pw));
    } catch (e) {
      print('Login failed: $e');
    }
  }
}
Try it yourself: Add a third password.
Add to the list.
MEDIUMReal project: home screen loading many partsExample 7 of 10

Parallel downloads

Future.wait runs jobs together. Total time is the slowest job.
Future<String> load(String part, int sec) async {
  await Future.delayed(Duration(seconds: sec));
  print('$part ready');
  return part;
}

Future<void> main() async {
  var all = await Future.wait([load('Banner', 2), load('Profile', 1), load('Courses', 3)]);
  print('All loaded: $all');
}
Try it yourself: Add Notifications taking 1 second.
Add load('Notifications', 1).
MEDIUMReal project: protecting users from endless waitingExample 8 of 10

Timeout

timeout turns a very slow call into an error you can handle.
import 'dart:async';

Future<String> slow() async {
  await Future.delayed(Duration(seconds: 10));
  return 'data';
}

Future<void> main() async {
  try {
    var r = await slow().timeout(Duration(seconds: 2));
    print(r);
  } on TimeoutException {
    print('Server too slow. Please try again.');
  }
  print('App is still running');
}
Try it yourself: Make the timeout 20 seconds.
Change Duration(seconds: 2).
HARDReal project: weak networks in villages and small townsExample 9 of 10

Retry with delay

Retry up to three times, waiting longer each time (backoff). Good apps do exactly this.
int tries = 0;
Future<String> flaky() async {
  tries++;
  await Future.delayed(Duration(milliseconds: 100));
  if (tries < 3) throw Exception('No signal');
  return 'Saved on try $tries';
}
Future<String> retry(int max) async {
  for (int i = 1; i <= max; i++) {
    try {
      return await flaky();
    } catch (e) {
      print('Try $i failed: $e. Waiting ${i * 500} ms');
      await Future.delayed(Duration(milliseconds: i * 500));
    }
  }
  return 'Could not save';
}
Future<void> main() async {
  print(await retry(5));
}
Try it yourself: Allow only 2 retries.
retry(2)
HARDReal project: e-commerce checkoutExample 10 of 10

Order pipeline

Steps depend on each other so each is awaited in order; independent notifications run together at the end.
Future<bool> payment(double amt) async {
  await Future.delayed(Duration(milliseconds: 300));
  return amt <= 5000;
}
Future<String> createOrder() async {
  await Future.delayed(Duration(milliseconds: 200));
  return 'ORD-1042';
}
Future<void> send(String channel, String id) async {
  await Future.delayed(Duration(milliseconds: 100));
  print('$channel sent for $id');
}
Future<void> main() async {
  print('Checking payment...');
  if (!await payment(2499)) {
    print('Payment failed');
    return;
  }
  var id = await createOrder();
  print('Order $id created');
  await Future.wait([send('SMS', id), send('Email', id)]);
  print('Done');
}
Try it yourself: Try a payment of 9000.
payment(9000)

Quick quiz

3 questions. Click an answer.
What does await do?
Stops the whole appPauses this function until the Future completesDeletes the FutureStarts a loop
What does an async function return?
void onlyA FutureA Mapnull
How long does Future.wait take for jobs of 1, 2 and 3 seconds?
6 secondsAbout 3 seconds1 second2 seconds
Score: 0 / 3

Recap: what you learned in Module 15

Future

A promise of a value later.

async / await

Write slow code like normal code, top to bottom.

Errors

try/catch around await; timeout for slow calls.

Future.wait

Run tasks in parallel; time is the slowest.

Order

Normal code, microtasks, then timers.

Apps

Loading screens, retries, order pipelines.

Next: Streams, Generators and Timers - Many values over time: Stream, listen, async*, sync*, StreamController, Timer
MODULE 16 · PART 4

Streams, Generators and Timers

Many values over time: Stream, listen, async*, sync*, StreamController, Timer
You will learn
  • Stream: many values over time
  • Listen to a stream and use await for
  • Stream transforms: map, where, take
  • Generators: sync* and async*
  • StreamController and broadcast streams
  • Timers: periodic and one-shot
You will build: a live score ticker, a chat message stream and a stopwatch
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🌊

Where is this used in real apps?

A Future gives ONE value later. A Stream gives MANY values over time: chat messages, live cricket score, GPS location, sensor readings. You listen, and each new value arrives as an event.

Chat apps

Every new message arrives on a stream.

Live scores

The scoreboard listens to a stream of updates.

Sensors and GPS

Location updates keep coming; the map listens.

Live Score
🏏
IND 134/3
over 15.2
🏏
IND 138/3
over 15.4
🏏
IND 144/3
over 16.0

Stream with await for

An async* function yields values one at a time. await for receives each value as it comes.

Future vs Stream: Future = one parcel; Stream = a conveyor belt of parcels.
Stream<int> countdown() async* {
  for (int i = 3; i >= 1; i--) {
    await Future.delayed(Duration(milliseconds: 500));
    yield i;
  }
}

Future<void> main() async {
  await for (var n in countdown()) {
    print('Tick $n');
  }
  print('Stream finished');
}

listen

stream.listen(callback) calls your function for every value. onDone runs at the end and onError handles errors.

Note: "Listening..." prints first because listen does not wait.
Stream<String> messages() async* {
  for (var m in ['Hi', 'How are you?', 'Bye']) {
    await Future.delayed(Duration(milliseconds: 300));
    yield m;
  }
}

void main() {
  messages().listen(
    (m) => print('New message: $m'),
    onDone: () => print('Chat closed'),
  );
  print('Listening...');
}

Transforming streams

Streams have map, where, take, skip just like lists, plus toList(), first, length that give a Future.

Real use: keep only the messages from one friend: where.
Stream<int> numbers() => Stream.fromIterable([1, 2, 3, 4, 5, 6, 7, 8]);

Future<void> main() async {
  var evens = numbers().where((n) => n.isEven).map((n) => n * 10);
  print(await evens.toList());
  print(await numbers().take(3).toList());
  print(await numbers().length);
  print(await numbers().first);
}

sync* generators

sync* makes a lazy list: values are produced only when needed, so even endless sequences are possible. yield* hands over another sequence.

naturals() never ends, but take(5) asks for only five.
Iterable<int> evens(int max) sync* {
  for (int i = 2; i <= max; i += 2) {
    yield i;
  }
}

Iterable<int> naturals() sync* {
  int n = 1;
  while (true) {
    yield n++;
  }
}

void main() {
  print(evens(10).toList());
  print(naturals().take(5).toList());
}

StreamController

A StreamController lets your own code push values into a stream with add. A broadcast stream allows many listeners.

Real use: two screens listening to the same live data.
import 'dart:async';

void main() {
  var ctrl = StreamController<String>.broadcast();
  ctrl.stream.listen((m) => print('Screen A got: $m'));
  ctrl.stream.listen((m) => print('Screen B got: $m'));
  ctrl.add('Score 50');
  ctrl.add('Score 54');
  ctrl.close();
}

Timers

Timer(duration, fn) runs once later. Timer.periodic repeats; call cancel() to stop it.

Real use: auto-refresh every 30 seconds; countdown for OTP.
import 'dart:async';

void main() {
  Timer(Duration(milliseconds: 1200), () => print('One-shot after 1.2 sec'));
  int ticks = 0;
  Timer.periodic(Duration(milliseconds: 500), (t) {
    ticks++;
    print('Tick $ticks');
    if (ticks == 4) {
      t.cancel();
      print('Stopped');
    }
  });
}

Animated explainer: Future vs Stream

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

Animated explainer: Broadcast to many listeners

Press Next to walk through it step by step, or Auto play.
EASYReal project: OTP resend timerExample 1 of 10

Countdown stream

A stream gives one number per tick. await for prints each one.
Stream<int> count(int from) async* {
  for (int i = from; i >= 1; i--) {
    await Future.delayed(Duration(milliseconds: 400));
    yield i;
  }
}

Future<void> main() async {
  await for (var n in count(5)) {
    print('Resend OTP in $n');
  }
  print('You can resend now');
}
Try it yourself: Count down from 3.
count(3)
EASYReal project: turning data into a flowExample 2 of 10

Stream from list

Stream.fromIterable makes a stream from any list.
Future<void> main() async {
  var s = Stream.fromIterable(['Asha', 'Rohit', 'Meena']);
  await for (var name in s) {
    print('Welcome $name');
  }
}
Try it yourself: Use numbers 1 to 5.
Stream.fromIterable([1,2,3,4,5])
EASYReal project: lazy number sequencesExample 3 of 10

Generator with sync*

yield hands out one value at a time.
Iterable<int> table(int n) sync* {
  for (int i = 1; i <= 10; i++) {
    yield n * i;
  }
}

void main() {
  print(table(7).toList());
  print(table(12).take(3).toList());
}
Try it yourself: Make squares(n).
yield i * i;
EASYReal project: delayed actions like "Undo" barsExample 4 of 10

One-shot timer

A timer runs a function once after a wait.
import 'dart:async';

void main() {
  print('Message sent. Undo available...');
  Timer(Duration(seconds: 2), () => print('Undo no longer possible'));
  print('Main finished first');
}
Try it yourself: Change to 1 second.
Duration(seconds: 1)
EASYReal project: live clocks and auto refreshExample 5 of 10

Periodic ticks

Timer.periodic repeats until cancelled.
import 'dart:async';

void main() {
  int n = 0;
  Timer.periodic(Duration(milliseconds: 400), (t) {
    n++;
    print('Refresh #$n');
    if (n == 3) t.cancel();
  });
}
Try it yourself: Stop after 5 refreshes.
if (n == 5) t.cancel();
MEDIUMReal project: sports appsExample 6 of 10

Live score ticker

A stream of scores; the screen reacts to each update.
Stream<String> score() async* {
  int runs = 120;
  for (int over = 15; over <= 18; over++) {
    await Future.delayed(Duration(milliseconds: 400));
    runs += 7 + over % 3;
    yield 'Over $over: IND $runs/3';
  }
}

Future<void> main() async {
  await for (var s in score()) {
    print(s);
  }
  print('Innings over');
}
Try it yourself: Add wickets that increase.
Keep a wickets variable.
MEDIUMReal project: chat filters and notificationsExample 7 of 10

Filter and transform

where and map work on streams like lists.
Future<void> main() async {
  var messages = Stream.fromIterable(['hi', 'BUY NOW!!!', 'class at 5', 'WIN MONEY', 'ok']);
  var clean = messages.where((m) => m != m.toUpperCase()).map((m) => 'Allowed: $m');
  await for (var m in clean) {
    print(m);
  }
}
Try it yourself: Block messages containing 'class'.
Add && !m.contains('class')
MEDIUMReal project: running totals in dashboardsExample 8 of 10

Sum from a stream

fold and reduce turn a stream into one final value.
Future<void> main() async {
  var sales = Stream.fromIterable([1200, 800, 450, 2100]);
  int total = await sales.fold(0, (a, b) => a + b);
  print('Total sales: Rs $total');
  var maxSale = await Stream.fromIterable([1200, 800, 450, 2100]).reduce((a, b) => a > b ? a : b);
  print('Biggest sale: Rs $maxSale');
}
Try it yourself: Find the smallest sale.
Use a < b.
HARDReal project: messaging appsExample 9 of 10

Chat room with broadcast

Two users listen to the same controller. Messages sent after listening are received by both.
import 'dart:async';

void main() async {
  var room = StreamController<String>.broadcast();
  room.stream.listen((m) => print('[Asha sees] $m'));
  room.stream.where((m) => m.contains('Rohit')).listen((m) => print('[Rohit notified] $m'));
  for (var m in ['Welcome to class chat', 'Rohit, please join', 'Class starts at 5']) {
    room.add(m);
    await Future.delayed(Duration(milliseconds: 100));
  }
  await room.close();
  print('Room closed');
}
Try it yourself: Add a listener for the word class.
where((m) => m.contains('class'))
HARDReal project: timers in fitness and exam appsExample 10 of 10

Stopwatch with periodic timer

A periodic timer updates a counter; after 5 ticks it cancels itself and prints the total time.
import 'dart:async';

void main() {
  int seconds = 0;
  Timer.periodic(Duration(seconds: 1), (t) {
    seconds++;
    String mm = (seconds ~/ 60).toString().padLeft(2, '0');
    String ss = (seconds % 60).toString().padLeft(2, '0');
    print('Elapsed $mm:$ss');
    if (seconds == 5) {
      t.cancel();
      print('Stopped at $seconds seconds');
    }
  });
}
Try it yourself: Stop at 8 seconds.
if (seconds == 8)

Quick quiz

3 questions. Click an answer.
What is a Stream?
One value laterMany values over timeA listA class
Which keyword delivers a value from an async* function?
returnyieldsendemit
How do you stop a periodic Timer?
t.stop()t.cancel()t.end()break
Score: 0 / 3

Recap: what you learned in Module 16

Stream

Many values over time. Listen or await for.

Transforms

where, map, take, toList, fold.

Generators

sync* gives lazy lists, async* gives streams; both use yield.

Controller

Push your own values; broadcast for many listeners.

Timers

Timer for once, Timer.periodic to repeat; cancel to stop.

Use

Chat, scores, sensors, auto refresh.

Next: the next part of the course.

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