Thuta Learning
Dart
AdvancedProgrammingBeginner

Futures, Streams & Async Errors

DartLesson 2235 min

What you'll walk away with

  • Decide when to use a Future and when to use a Stream
  • Produce values with async* and StreamController, and close the controller
  • Consume a stream with await for and listen(onData, onError, onDone)
  • Explain the difference between single-subscription and broadcast streams
  • Handle async errors with try/catch, catchError, timeout and Future.wait

Explain it simply

Explain it simply

A Future is like a parcel: one delivery, one doorbell, and it is over. A Stream is like the conveyor belt at a sushi restaurant. Dishes keep arriving over time, and you decide whether to take each one.

When the kitchen closes the belt stops, which is the done event. Sometimes a spoiled dish arrives, which is an error event, yet the belt keeps moving. Anything that delivers more than one thing over time fits a Stream: chat messages, key presses, chunks of a download, timer ticks.

Problem → Why → Solution

The problem: one answer is not enough

Suppose a countdown screen needs the values 3, 2, 1, one per second. A Future cannot do that: it completes once, and a function can return only once. That is the job of a Stream, a sequence of asynchronous events. But streams come with a first trap of their own.

You add a second listener, say one for the UI and one for a logger, and the program crashes with 'Bad state: Stream has already been listened to.'

two_listeners.dart
import 'dart:async';

void main() {
  final messages = StreamController<String>();
  messages.stream.listen((m) => print('ui: $m'));
  messages.stream.listen((m) => print('log: $m')); // second listener throws
  messages.add('hello');
}

Why only one listener?

A default stream (single-subscription) hands its events to exactly one listener, because it may hold events until someone listens and cannot tell which of several listeners should receive them. Several listeners need a broadcast stream, which makes a different promise: events go to whoever is listening right now, and nothing is replayed.

Core concept: one value or many

A Stream<T> is a source that delivers events in order. There are three kinds: data events carrying a value of type T, error events, and finally one done event. Done appears once, and nothing follows it. An error event does not have to end the stream; data can keep arriving after it.

Future<T>Stream<T>
How many valuesOne value or one errorZero to many
How you waitawaitawait for, or listen
How it endsCompletes, doneA done event after close()

A quick way to choose is to count the answers you expect. One answer, even a slow one, is a Future. A series of answers, or an answer that repeats whenever something changes, is a Stream. A list returned by a Future is still one answer, while a Stream of items lets the consumer start working on the first item before the last one exists.

There are two main ways to produce a stream. Inside an async* function you hand out one value at a time with yield. That function only starts running when someone listens and stops when nobody wants the next value, so it is lazy. The other way is a StreamController: you push outside events (taps, network messages) with add(value), push failures with addError(error), and send done with close(). If you never call close(), the stream never finishes.

There are also two ways to consume one. await for hands you each event in order like a normal loop, and an error event is thrown at the loop and ends it, so a try/catch around the loop can catch it. listen(onData, onError: ..., onDone: ...) is the callback style; it returns a StreamSubscription whose cancel() stops it early. If you pass no onError, an error event becomes an unhandled exception and ends the program.

Mental model: a conveyor belt
  1. A stream sends data, error, done events
  2. Producer: async* or a controller
  3. Consumer: await for or listen
  4. close() sends done; cancel() stops early

Whoever builds the belt must close it, and whoever stops caring must cancel; remember both.

General pattern

dart
Stream<T> generate() async* {
  yield value;                       // one data event
}

final controller = StreamController<T>();   // or .broadcast()
controller.add(value);
controller.addError(error);
controller.close();                  // sends done

await for (final item in stream) { /* each data event */ }
stream.listen(onData, onError: onError, onDone: onDone);

async* produces values with yield; a StreamController produces them with add, addError and close. You consume with await for or listen.

A countdown and a live feed

The first half builds a countdown stream with async* and consumes it with await for. The second half creates a StreamController and uses listen to record data, error and done in separate places. Watch how one event is an error and data still arrives after it.

There is a single listener and plain awaits, so the order in which events arrive cannot change. All printing happens at the end from one place, so the output is the same on every run.

streams.dart
import 'dart:async';

Stream<int> countdown(int from) async* {
  for (var n = from; n > 0; n--) {
    await Future.delayed(Duration(milliseconds: 20));
    yield n;
  }
}

Future<void> main() async {
  final ticks = <int>[];
  await for (final n in countdown(3)) {
    ticks.add(n);
  }
  print('countdown: $ticks');

  final controller = StreamController<String>();
  final values = <String>[];
  final errors = <String>[];
  final finished = Completer<void>();

  controller.stream.listen(
    values.add,
    onError: (Object e) => errors.add('$e'),
    onDone: finished.complete,
  );

  controller.add('first');
  controller.addError(StateError('bad packet'));
  controller.add('second');
  await controller.close();
  await finished.future;

  print('values: $values');
  print('errors: $errors');
}

Code breakdown

  1. A generator functionStream<int> countdown(int from) async* {

    async* marks a generator function that produces a stream. The return type is Stream<int> and the body uses yield. Calling it does not run the body yet; it starts when someone listens.

  2. Emitting a valueyield n;

    yield emits one data event and the function continues after the consumer has taken it. Unlike return, the function is not finished.

  3. Consuming with a loopawait for (final n in countdown(3)) {

    await for waits for each event and runs the loop body once per data event. The loop ends only when the stream sends done.

  4. A controller you push intofinal controller = StreamController<String>();

    A StreamController is not the stream itself. You read the stream from controller.stream and push events in with controller.add.

  5. Handling every event kindonError: (Object e) => errors.add('$e'),

    In this listen call onData is values.add, onError is this callback and onDone is finished.complete. With onError present, an error event lands in the errors list instead of ending the program.

  6. Pushing an errorcontroller.addError(StateError('bad packet'));

    addError sends an error event instead of data. The stream stays usable, so 'second' still arrives afterwards.

  7. Closing the streamawait controller.close();

    close() sends the done event. Without it, finished would never complete. Awaiting close() on a controller that has no listener also never completes.

You should see
countdown: [3, 2, 1]
values: [first, second]
errors: [Bad state: bad packet]
Life of a stream
  1. A producer builds the stream
  2. A consumer listens or uses await for
  3. Data and error events flow in order
  4. close() sends done and onDone runs

Consumed to the end

A done event arrives and the await for loop finishes.

Stopped early

break, take(n) or subscription.cancel() stops the producer.

Single-subscription or broadcast?

Plain StreamController and async* streams are single-subscription: one listener, and a second one fails with the error from the problem section. StreamController.broadcast() or stream.asBroadcastStream() allows many listeners, but each listener only receives events that happen after it subscribed.

In the code below a subscribed early, so it gets 1, 2 and 3, while b subscribed after event 1 and gets only 2 and 3. Each listener writes to its own list and everything prints at the end, so nothing depends on interleaving.

broadcast.dart
import 'dart:async';

Future<void> main() async {
  final single = StreamController<int>();
  single.stream.listen((_) {});
  try {
    single.stream.listen((_) {});
  } on StateError catch (e) {
    print('single: $e');
  }
  await single.close();

  final live = StreamController<int>.broadcast();
  final a = <int>[];
  final b = <int>[];
  live.stream.listen(a.add);
  live.add(1);
  await Future.delayed(Duration.zero); // let event 1 reach a
  live.stream.listen(b.add);
  live.add(2);
  live.add(3);
  await live.close();
  print('a: $a');
  print('b: $b');
}
text
single: Bad state: Stream has already been listened to.
a: [1, 2, 3]
b: [2, 3]
Single-subscriptionBroadcast
ListenersExactly oneAny number
Events before listeningBuffered, then deliveredLost
Typical sourceFile reads, async*UI events, controller.broadcast()

Streams are lazy

where(), map() and take() just return a new stream. The async* body does not start until someone really listens. A break inside await for cancels the subscription and stops the producer too, so jobs that do not need everything, such as 'I only want the first two', never do extra work.

lazy.dart
Stream<int> squares() async* {
  for (final value in [1, 2, 3, 4, 5]) {
    await Future<void>.delayed(Duration.zero);
    print('producing $value');
    yield value * value;
  }
}

Future<void> main() async {
  final evens = squares().where((v) => v.isEven).map((v) => 'sq=$v');
  print('pipeline built, nothing produced yet');
  print(await evens.toList());

  print('--- break stops the producer');
  await for (final v in squares()) {
    print('got $v');
    if (v >= 4) break;
  }
  print('after break');
}
text
pipeline built, nothing produced yet
producing 1
producing 2
producing 3
producing 4
producing 5
[sq=4, sq=16]
--- break stops the producer
producing 1
got 1
producing 2
got 4
after break

Future errors: try/catch, catchError, timeout, wait

await with try/catch is the easiest, but you should also be able to read the callback style, .catchError. On a Future<int>, the handler passed to catchError must return an int (or a Future<int>); otherwise an ArgumentError appears at runtime. .timeout(duration) turns an over-slow Future into a TimeoutException. Future.wait fails with that error as soon as one of the Futures it is given fails.

future_errors.dart
import 'dart:async';

Future<int> parsePort(String text) async {
  await Future.delayed(Duration(milliseconds: 10));
  return int.parse(text);
}

Future<void> main() async {
  try {
    await parsePort('80x');
  } on FormatException catch (e) {
    print('try/catch: ${e.message}');
  }

  final fallback = await parsePort('oops').catchError((Object e) => 8080);
  print('catchError fallback: $fallback');

  final slow = Future<int>.delayed(Duration(milliseconds: 200), () => 1);
  try {
    await slow.timeout(Duration(milliseconds: 30));
  } on TimeoutException {
    print('timed out');
  }

  try {
    await Future.wait([parsePort('1'), parsePort('x'), parsePort('3')]);
  } on FormatException catch (e) {
    print('wait failed: ${e.message}');
  }
}
text
try/catch: Invalid radix-10 number
catchError fallback: 8080
timed out
wait failed: Invalid radix-10 number

The catchError return type

Writing failing().catchError((e) { print(e); }) gives a handler that returns nothing (null). The Future<int> expects an int, so an ArgumentError with the text 'The error handler of Future.catchError must return a value of the future's type' appears. This trap is a big reason people prefer await with try/catch.

In real projects

In real projects

Streams run through the whole Dart ecosystem. In dart:io, File.openRead() returns a Stream of chunks, stdin is a stream of terminal input, and WebSocket and HttpServer are streams too. In Flutter the StreamBuilder widget rebuilds the UI on every new event. Many state-management libraries also expose state changes as streams. Command-line tools commonly pipe stdin through utf8.decoder and LineSplitter to process input line by line without loading it all into memory.

In a real app the common stream problems are not running out of events but errors arriving and listeners never being released. So always add onError, cancel the subscription when the widget goes away, and close any controller you created. Give network calls a timeout as well, so a silent server does not leave the screen loading forever.

Common mistakes

Common mistakes

Never closing a StreamController

If you add two values, never close, and write await for (final v in c.stream), the loop keeps waiting for done. Run it and you see only 'got 1' and 'got 2'; nothing after the loop runs, and the program simply exits without an error. Awaiting c.close() on a controller with no listener behaves the same way.

Listening without onError

With c.stream.listen((v) => print(v)) and a later c.addError(StateError('bad')), nothing handles the error, so 'Unhandled exception: Bad state: bad' appears and the program stops. Add onError to every listen on a stream whose producer can send errors, and wrap await for in try/catch.

Expecting a broadcast stream to replay

If you call add(1) and add(2) on a broadcast controller and only then listen, you never receive 1 or 2; in a quick test, only a later add(3) arrives. If a screen also needs the latest value when it opens, store that value yourself and hand it over at subscribe time.

A catchError handler with the wrong return type

On a Future<int>, catchError((e) { print(e); }) returns null from the handler and raises an ArgumentError. Return an int fallback from the handler, or use try/catch, where nothing needs to be returned.

Best practices

Best practices

  • Use a Future for one result and a Stream for many results over time.
  • Decide where every StreamController you create will be closed before you finish writing it.
  • Keep a single-subscription stream for one listener; make it broadcast when you need several.
  • Put a timeout on anything that can be slow, such as network calls.

Mini challenge

A sensor feed pipeline

Turn a sensor's readings into a stream. The value -1 means 'no reading' and must be left out of the average. Compute the average with await for, stop a stream early with take, and handle the case of an empty stream.

  • sensor(readings) is an async* function that waits 10 ms and yields each value
  • average(stream) uses await for to collect a sum and a count and returns a double, 0 for an empty stream
  • main() filters out the -1 values with where and prints the average
  • It also prints the first two values using take(2).toList() and the average of an empty stream
sensor.dart
Stream<int> sensor(List<int> readings) async* {
  // TODO: for each reading, wait 10 ms, then yield it
}

Future<double> average(Stream<int> readings) async {
  // TODO: loop with await for, keep a running sum and a count
  // TODO: return 0 when nothing arrived, otherwise sum / count
}

Future<void> main() async {
  final raw = [4, -1, 8, -1, 12];
  // TODO: print the average of raw with every -1 filtered out (where)
  // TODO: print the first two raw values using take(2) and toList()
  // TODO: print the average of an empty stream
}

Expected: Three lines: average: 8.0, first two: [4, -1] and empty: 0.0.

Show hint

sensor(raw).where((r) => r >= 0) gives a new stream without the -1 values. In Dart, int / int already produces a double, so write sum / count, but never divide when count is 0.

Show solution
sensor.dart
Stream<int> sensor(List<int> readings) async* {
  for (final r in readings) {
    await Future.delayed(Duration(milliseconds: 10));
    yield r;
  }
}

Future<double> average(Stream<int> readings) async {
  var sum = 0;
  var count = 0;
  await for (final r in readings) {
    sum += r;
    count++;
  }
  return count == 0 ? 0 : sum / count;
}

Future<void> main() async {
  final raw = [4, -1, 8, -1, 12];
  final valid = sensor(raw).where((r) => r >= 0);
  print('average: ${await average(valid)}');
  print('first two: ${await sensor(raw).take(2).toList()}');
  print('empty: ${await average(sensor([]))}');
}

Quick quiz 1 / 3

What happens when you call listen twice on the stream of a plain StreamController<String>()?

Quick quiz 2 / 3

You add(1) and add(2) to a controller, never call close(), and run await for (final v in c.stream). What happens?

Quick quiz 3 / 3

On a broadcast controller you add(1), add(2), then subscribe a listener, then add(3). What does the listener receive?

What to remember

  • A Future gives one value; a Stream gives a sequence of data, error and done events
  • async* is lazy, and a StreamController must be closed by you or await for never finishes
  • A plain stream has one listener; a broadcast stream has many but never replays past events
  • Handle errors with try/catch and onError, keep catchError return types right, and add timeouts

Asynchronous programming: Streams — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Futures, Streams & Async Errors | Thuta Learning