Reusable type-safe code, add methods to existing types, custom operators · 6 h
try, catch, finally, throw, custom exceptions and defensive programming · 6 h
Do slow work without freezing: Future, async/await, timers, parallel tasks · 7 h
Many values over time: Stream, listen, async*, sync*, StreamController, Timer · 6 h
25 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi
List
'9876543210'.isValidPhone is an extension you write once.
Money, Fraction and Vector use + - * operators.
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.
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);
}Functions can be generic too. A bound restricts T: T extends num allows only int and double, so you may use maths inside.
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 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.
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);
}Define operator +, operator -, operator ==, operator [] to teach your class what the symbols mean.
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 gives a short name to a function type. A class with a call method can be used like a function.
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));
}A stack is last-in, first-out like a pile of plates. Written once with a generic, it works for any type.
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);
}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]));
}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);
}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);
}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);
}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);
}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));
}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()}');
}
}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]));
}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})');
}
}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);
}Box
T extends num limits types and unlocks maths.
Add methods to existing types.
operator + - * == [] for your classes.
Callable objects and short function-type names.
Generic LIFO and FIFO structures.
If the bank is down, show a message and do not charge twice.
Catch bad numbers typed by a user.
Handle timeout, no internet, wrong data.
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 *).
Missing semicolon or bracket. The editor shows a red line.
int.parse('abc') throws FormatException while running.
Total = price + qty instead of price * qty. No crash, wrong bill!
Put risky code in try. If it throws, Dart jumps to catch. finally always runs, success or failure: perfect for cleanup.
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');
}on FormatException catch (e) handles only that type. Add several on blocks for different problems, and a plain catch last for the rest.
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 raises an exception yourself. Make your own class that implements Exception to give clear, meaningful names to problems.
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 passes an error on after you log it. assert(condition, message) checks assumptions while developing.
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');
}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.
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'));
}void main() {
try {
int age = int.parse('twenty');
print(age);
} catch (e) {
print('Please type digits only');
}
print('Form still works');
}void main() {
print('Opening file');
try {
print('Reading...');
throw Exception('Disk error');
} catch (e) {
print('Error: $e');
} finally {
print('Closing file');
}
}void main() {
for (var t in ['12', 'x9', '', '7.5', ' 40 ']) {
int? n = int.tryParse(t.trim());
print('"$t" -> ${n ?? 'invalid'}');
}
}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);
}
}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');
}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');
}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);
}
}
}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');
}
}
}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));
}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);
}Syntax, runtime and logic errors.
Handle problems without crashing; finally always runs.
Handle specific exceptions separately.
Raise your own errors; custom classes implement Exception.
Log then pass on; check assumptions in debug mode.
Validate early; tryParse; never an empty catch.
Load courses from a server while a spinner is shown.
Read a big file without freezing the screen.
Wait for the bank reply, then show success.
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.
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');
}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.
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');
}Use try/catch around await. .timeout() fails a Future that takes too long. TimeoutException needs import 'dart:async'.
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');
}
}Start many Futures at once and wait for all. Total time is the slowest one, not the sum.
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');
}Awaiting one after another adds the times. Starting first and awaiting later runs them together.
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)');
}Dart runs normal code first. Then microtasks (scheduleMicrotask, Future.value). Then events like timers (Future.delayed, Timer).
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');
}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');
}void main() {
Future.delayed(Duration(seconds: 1), () => 42).then((v) {
print('Value arrived: $v');
});
print('Not blocked');
}Future<void> main() async {
for (int i = 3; i >= 1; i--) {
print('$i...');
await Future.delayed(Duration(seconds: 1));
}
print('Go!');
}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);
}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');
}
}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');
}
}
}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');
}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');
}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));
}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');
}A promise of a value later.
Write slow code like normal code, top to bottom.
try/catch around await; timeout for slow calls.
Run tasks in parallel; time is the slowest.
Normal code, microtasks, then timers.
Loading screens, retries, order pipelines.
Every new message arrives on a stream.
The scoreboard listens to a stream of updates.
Location updates keep coming; the map listens.
An async* function yields values one at a time. await for receives each value as it comes.
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');
}stream.listen(callback) calls your function for every value. onDone runs at the end and onError handles errors.
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...');
}Streams have map, where, take, skip just like lists, plus toList(), first, length that give a Future.
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* makes a lazy list: values are produced only when needed, so even endless sequences are possible. yield* hands over another sequence.
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());
}A StreamController lets your own code push values into a stream with add. A broadcast stream allows many listeners.
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();
}Timer(duration, fn) runs once later. Timer.periodic repeats; call cancel() to stop it.
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');
}
});
}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');
}Future<void> main() async {
var s = Stream.fromIterable(['Asha', 'Rohit', 'Meena']);
await for (var name in s) {
print('Welcome $name');
}
}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());
}import 'dart:async';
void main() {
print('Message sent. Undo available...');
Timer(Duration(seconds: 2), () => print('Undo no longer possible'));
print('Main finished first');
}import 'dart:async';
void main() {
int n = 0;
Timer.periodic(Duration(milliseconds: 400), (t) {
n++;
print('Refresh #$n');
if (n == 3) t.cancel();
});
}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');
}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);
}
}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');
}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');
}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');
}
});
}Many values over time. Listen or await for.
where, map, take, toList, fold.
sync* gives lazy lists, async* gives streams; both use yield.
Push your own values; broadcast for many listeners.
Timer for once, Timer.periodic to repeat; cancel to stop.
Chat, scores, sensors, auto refresh.