DartIntermediate 2 min read

Dart streams: events, await for and cancellation

Consume a stream with await for and understand subscription ownership, cancellation and event errors.

On this page

A future describes one eventual result. A stream can deliver a sequence of events over time, such as messages, sensor readings or progress updates.

Produce and consume events

main.dart
Stream<int> practiceTicks() async* {
  for (var tick = 1; tick <= 3; tick++) {
    await Future<void>.delayed(const Duration(milliseconds: 300));
    yield tick;
  }
}

Future<void> main() async {
  await for (final tick in practiceTicks()) {
    print('Practice step $tick');
  }
  print('Session complete.');
}

Decide who owns a subscription

With listen, you receive a subscription that can be canceled. If a screen starts listening to a long-lived source, the screen should stop listening when it no longer needs the events.

In Flutter, StreamBuilder can connect a stream to visible states, but the underlying resource still needs a clear owner. Avoid creating a new source every time the widget builds.

Think about errors and completion

An event source can emit data, emit errors and eventually close. Decide what each means for your feature. A temporary error does not always mean the source is permanently finished.

Separate the event sequence from its consumer lifetime

The producer yields successive ticks and then closes. await for consumes that sequence until completion or an appropriate exit. A long-lived source can continue producing events after a particular screen no longer needs them, so listening through a subscription introduces ownership and cancellation decisions.

An error event and normal completion are not necessarily the same thing. Decide whether a feature can recover or should stop listening instead of treating every error as an empty result.

Connect that reasoning to Flutter lifecycle cleanup before attaching a stream to a screen. Keep the source stable rather than creating a fresh subscription each time build executes.

Try it yourself

Change the producer to emit five events. Stop consuming after the second. Then write down how you would cancel a subscription if the user navigated away from a screen.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Dart Streams - Flutter in Focus · Flutter · official channel

Preview image only. YouTube loads when you press Play.

A conceptual introduction to Dart streams. Pair it with the current subscription, error and cancellation examples in this course. Watch on YouTube

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.