Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 16 of 19 · 5 min read

Dart streams, generators and timers

Dart streams notes with examples: listen and await for, map, where and take, sync* and async* generators, StreamController, broadcast streams and Timer.

Stream: many values over time

A Future gives one value later. A Stream gives many values over time: chat messages, live cricket scores, a download's progress, taps on a button, a sensor's readings.

One valueMany values
Now (synchronous)intIterable<int> (a list)
Later (asynchronous)Future<int>Stream<int>

Listening to a stream

Future<void> main() async {
  var ticks = Stream.periodic(Duration(milliseconds: 100), (i) => i + 1).take(3);
  var sub = ticks.listen((n) => print('Tick $n'));
  await sub.asFuture();   // completes when the stream is done
  print('Done');
}
Tick 1
Tick 2
Tick 3
Done

listen registers a function that runs for each value. It returns a StreamSubscription, which can pause, resume or cancel the stream. listen also takes onError and onDone callbacks; asFuture() gives a Future that completes when the stream ends (it replaces any onDone).

await for

Inside an async function, await for loops over a stream like a for-in loop, waiting for each value:

Stream<int> countdown(int from) =>
    Stream.periodic(Duration(milliseconds: 100), (i) => from - i).take(from);

Future<void> main() async {
  await for (var n in countdown(3)) {
    print(n);
  }
  print('Lift off!');
}
3
2
1
Lift off!

The loop ends when the stream is done. break inside it cancels the subscription.

Transforming streams

Streams have the same helpers as lists: map, where, take, skip, and more. Each returns a new stream.

Future<void> main() async {
  var scores = Stream.fromIterable([4, 0, 6, 1, 4, 6, 2]);
  var boundaries = scores.where((r) => r == 4 || r == 6).map((r) => '$r runs!').take(3);
  await for (var b in boundaries) {
    print(b);
  }
  var total = await Stream.fromIterable([4, 0, 6, 1]).reduce((a, b) => a + b);
  print('Total: $total');
}
4 runs!
6 runs!
4 runs!
Total: 11

Stream.fromIterable turns a list into a stream, handy for testing. toList(), first, length and reduce return Futures.

Generators: sync* and async*

A generator function produces values one at a time with yield.

  • sync* returns an Iterable (values on demand, now).
  • async* returns a Stream (values over time); it may use await.
Iterable<int> evens(int max) sync* {
  for (int i = 2; i <= max; i += 2) {
    yield i;
  }
}

Stream<String> progress() async* {
  for (int p = 25; p <= 100; p += 25) {
    await Future.delayed(Duration(milliseconds: 100));
    yield 'Downloaded $p%';
  }
}

Future<void> main() async {
  print(evens(10).toList());
  await for (var msg in progress()) {
    print(msg);
  }
}
[2, 4, 6, 8, 10]
Downloaded 25%
Downloaded 50%
Downloaded 75%
Downloaded 100%

yield* passes on every value of another iterable or stream.

StreamController

A StreamController lets your code push values into a stream: add sends a value, addError an error, and close ends the stream.

import 'dart:async';

class ChatRoom {
  final _controller = StreamController<String>();
  Stream<String> get messages => _controller.stream;
  void send(String from, String text) => _controller.add('$from: $text');
  void close() => _controller.close();
}

Future<void> main() async {
  var room = ChatRoom();
  var done = room.messages.forEach(print);
  room.send('Asha', 'Hi!');
  room.send('Rohit', 'Hello Asha');
  room.close();
  await done;
  print('Chat closed');
}
Asha: Hi!
Rohit: Hello Asha
Chat closed

Values added before anyone listens are buffered and delivered once a listener arrives.

Broadcast streams

A normal (single-subscription) stream allows only one listener; a second listen throws *Bad state: Stream has already been listened to.* A broadcast stream allows many, like a radio station:

import 'dart:async';

Future<void> main() async {
  var scores = StreamController<int>.broadcast();
  scores.stream.listen((s) => print('Screen 1: $s'));
  scores.stream.listen((s) => print('Screen 2: $s'));
  scores.add(150);
  scores.add(151);
  await scores.close();
}
Screen 1: 150
Screen 2: 150
Screen 1: 151
Screen 2: 151

Broadcast streams do not buffer: a listener that joins late misses earlier values.

Timers

Timer (from dart:async) runs code later, once or repeatedly.

import 'dart:async';

void main() {
  Timer(Duration(milliseconds: 200), () => print('One-shot: reminder!'));
  int count = 0;
  Timer.periodic(Duration(milliseconds: 50), (t) {
    count++;
    print('Periodic tick $count');
    if (count == 3) t.cancel();
  });
}
Periodic tick 1
Periodic tick 2
Periodic tick 3
One-shot: reminder!

Always cancel a periodic timer when it is no longer needed, for example when a screen closes.

Common mistakes

  • Listening twice to a single-subscription stream.
  • Forgetting to close a StreamController, so await for loops never end.
  • Forgetting to cancel subscriptions and periodic timers: memory leaks in apps.
  • Using await for on a stream that never ends and expecting the code after it to run.
  • Returning a Stream from an async (not async*) function and using yield.

Key points

  • A Stream<T> delivers many values over time; a Future<T> delivers one.
  • listen and await for consume streams; map, where and take transform them.
  • sync* generators make Iterables; async* generators make Streams; both use yield.
  • StreamController pushes values into a stream; .broadcast() allows many listeners.
  • Timer and Timer.periodic run code later; cancel what you start.

Practice questions

1. Write a sync* generator that yields the first n square numbers.
Iterable<int> squares(int n) sync* {
  for (int i = 1; i <= n; i++) {
    yield i * i;
  }
}

void main() {
  print(squares(5).toList());   // [1, 4, 9, 16, 25]
}
2. What is the difference between a Future and a Stream?

A Future produces one value (or error) later; a Stream produces a sequence of values (and errors) over time, until it is done.

3. Use Stream.fromIterable and where to print only the odd numbers from 1 to 7.
Future<void> main() async {
  await for (var n in Stream.fromIterable([1, 2, 3, 4, 5, 6, 7]).where((n) => n.isOdd)) {
    print(n);
  }
}

Prints 1, 3, 5 and 7.

4. Why does a second listen on StreamController<int>().stream throw?

It is a single-subscription stream, which allows one listener only. Use StreamController<int>.broadcast() for several listeners.

5. Write an async* function that counts down from 3 to 1, one number every 100 ms.
Stream<int> countdown() async* {
  for (int i = 3; i >= 1; i--) {
    await Future.delayed(Duration(milliseconds: 100));
    yield i;
  }
}

Future<void> main() async {
  await for (var n in countdown()) {
    print(n);
  }
}