Streams

suggest change

A Future<T> delivers one value (or one error) later. A Stream<T> from dart:async delivers a sequence of events over time: zero or more data events, interleaved with any number of error events, and finally an optional "done" event. Streams are how Dart represents file contents being read, bytes arriving on a socket, WebSocket messages, timer ticks, UI events and the output of other processes.

Stream is the asynchronous counterpart of Iterable:

One value Many values
synchronous T Iterable<T> (pulled with for-in, see Iterators)
asynchronous Future<T> Stream<T> (pushed to listeners, consumed with await for or listen)

There are two kinds of streams:

This article covers consuming streams, the Stream API, creating streams with constructors and StreamController, broadcast streams, transformers and error handling. Writing streams with async* and yield is covered in depth in Sync and async generators. The examples were run with Dart 3.13.

Consuming a stream with await for

Inside an async function, await for runs the loop body once per data event and finishes when the stream sends done:

Future<void> main() async {
  final stream = Stream.fromIterable([1, 2, 3]);

  var sum = 0;
  await for (final n in stream) {
    print('got $n');
    sum += n;
  }
  print('sum=$sum');
}

Output:

got 1
got 2
got 3
sum=6

await for pauses the subscription while the body is busy awaiting something, so a slow loop slows down the producer instead of piling up events. break (or return, or an exception) cancels the subscription. An error event is rethrown at the loop, which then stops.

await for waits for done. If the stream never closes (a socket that stays open, a controller nobody closes) the code after the loop never runs. See Common mistakes below.

Creating streams from values, futures and timers

Stream has constructors for the common cases:

import 'dart:async';

Future<void> main() async {
  print(await Stream.fromIterable(['a', 'b']).toList());
  print(await Stream.value(42).toList());
  print(await Stream<int>.empty().toList());
  print(await Stream.fromFuture(Future.delayed(
      const Duration(milliseconds: 10), () => 'later')).toList());

  // events arrive in completion order, not list order
  print(await Stream.fromFutures([
    Future.delayed(const Duration(milliseconds: 30), () => 'slow'),
    Future.delayed(const Duration(milliseconds: 10), () => 'fast'),
  ]).toList());

  // one event every 50 ms; the callback turns the count into a value
  final ticks = Stream.periodic(
      const Duration(milliseconds: 50), (i) => 'tick $i');
  print(await ticks.take(3).toList());

  try {
    await Stream<int>.error(StateError('boom')).toList();
  } on StateError catch (e) {
    print('caught $e');
  }
}

Output:

[a, b]
[42]
[]
[later]
[fast, slow]
[tick 0, tick 1, tick 2]
caught Bad state: boom

The other big sources are async* generator functions, StreamController, and dart:io APIs such as File.openRead(), Socket, HttpServer, Process.stdout and stdin.

Listening with listen and StreamSubscription

await for is built on listen, the one abstract method of Stream. listen takes callbacks for data, error and done events and immediately returns a StreamSubscription, which you use to pause, resume and cancel:

import 'dart:async';

Future<void> main() async {
  final stream = Stream.periodic(
      const Duration(milliseconds: 20), (i) => i).take(10);

  final done = Completer<void>();
  late StreamSubscription<int> sub;
  sub = stream.listen(
    (n) {
      print('data $n');
      if (n == 1) {
        print('pausing');
        sub.pause(Future.delayed(const Duration(milliseconds: 100)));
      }
      if (n == 3) {
        print('cancelling');
        sub.cancel();
        done.complete();
      }
    },
    onError: (Object e) => print('error $e'),
    onDone: () => print('done'),
  );
  print('listen returned, isPaused=${sub.isPaused}');
  await done.future;
  print('main finished');
}

Output:

listen returned, isPaused=false
data 0
data 1
pausing
data 2
data 3
cancelling
main finished

Things to notice:

Prefer await for for straight-line code. Use listen when you need to keep receiving events after errors, to pause and resume explicitly, or to consume a stream without blocking the current function (for example, a server handling many sockets at once). Keep the subscription and cancel it when you're done, or the source stays alive. More on that in Cancellation and timeouts.

Transforming streams

Stream has most of the Iterable methods. The ones that return a Stream are lazy: they do nothing until the resulting stream is listened to, and then they listen to the source:

Stream<int> numbers() => Stream.fromIterable([1, 2, 2, 3, 4, 4, 4, 5, 6]);

Future<String> lookup(int id) async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  return 'user$id';
}

Future<void> main() async {
  print(await numbers().map((n) => n * 10).toList());
  print(await numbers().where((n) => n.isEven).toList());
  print(await numbers().distinct().toList());
  print(await numbers().expand((n) => [n, -n]).take(6).toList());
  print(await numbers().skip(2).takeWhile((n) => n < 5).toList());
  print(await numbers().skipWhile((n) => n < 4).toList());

  // asyncMap waits for each Future before handling the next event
  print(await numbers().distinct().take(3).asyncMap(lookup).toList());

  // asyncExpand: each event becomes a whole stream
  print(await Stream.fromIterable([1, 2, 3])
      .asyncExpand((n) => Stream.fromIterable(List.filled(n, n)))
      .toList());

  // a typical pipeline
  final result = numbers()
      .distinct()
      .where((n) => n.isOdd)
      .map((n) => 'odd:$n');
  await for (final s in result) {
    print(s);
  }
}

Output:

[10, 20, 20, 30, 40, 40, 40, 50, 60]
[2, 2, 4, 4, 4, 6]
[1, 2, 3, 4, 5, 6]
[1, -1, 2, -2, 2, -2]
[2, 3, 4, 4, 4]
[4, 4, 4, 5, 6]
[user1, user2, user3]
[1, 2, 2, 3, 3, 3]
odd:1
odd:3
odd:5

The stream-specific ones are:

Each transformation returns a new stream that wraps the previous one. The source is consumed when you listen to the end of the chain, so you can't reuse an intermediate single-subscription stream for a second chain.

Reducing a stream to a Future

The methods that return a Future listen to the stream, consume it (completely, or until they have their answer) and cancel the subscription:

Stream<int> numbers() => Stream.fromIterable([3, 1, 4, 1, 5, 9, 2, 6]);

Future<void> main() async {
  print('first: ${await numbers().first}');
  print('last: ${await numbers().last}');
  print('length: ${await numbers().length}');
  print('elementAt(2): ${await numbers().elementAt(2)}');
  print('firstWhere: ${await numbers().firstWhere((n) => n > 4)}');
  print('lastWhere: ${await numbers().lastWhere((n) => n < 4)}');
  print('contains 9: ${await numbers().contains(9)}');
  print('any even: ${await numbers().any((n) => n.isEven)}');
  print('every positive: ${await numbers().every((n) => n > 0)}');
  print('reduce max: ${await numbers().reduce((a, b) => a > b ? a : b)}');
  print('fold sum: ${await numbers().fold(0, (sum, n) => sum + n)}');
  print('join: ${await numbers().join('-')}');
  print('toSet: ${await numbers().toSet()}');

  await numbers().take(2).forEach((n) => print('forEach $n'));

  try {
    await Stream<int>.empty().first;
  } on StateError catch (e) {
    print('empty.first: $e');
  }
  final x = await numbers().firstWhere((n) => n > 100, orElse: () => -1);
  print('orElse: $x');
}

Output:

first: 3
last: 6
length: 8
elementAt(2): 4
firstWhere: 5
lastWhere: 2
contains 9: true
any even: true
every positive: true
reduce max: 9
fold sum: 31
join: 3-1-4-1-5-9-2-6
toSet: {3, 1, 4, 5, 9, 2, 6}
forEach 3
forEach 1
empty.first: Bad state: No element
orElse: -1

first, firstWhere, elementAt, any, contains and every stop listening as soon as they know the answer. last, length, toList, fold, reduce and join need the done event, so on a stream that never ends they never complete. first and single throw StateError on an empty stream; firstWhere and lastWhere take an orElse callback. drain() consumes and discards all events, which is useful when you must read a response body but don't need it.

StreamController

A StreamController<T> is a stream you feed by hand. You add events through the controller (or its sink) and give consumers controller.stream:

import 'dart:async';

Future<void> main() async {
  final controller = StreamController<String>();

  // events added before anyone listens are buffered
  controller.add('hello');
  controller.add('world');
  controller.addError(FormatException('bad input'));
  controller.add('again');
  controller.close();
  print('hasListener=${controller.hasListener}');

  controller.stream.listen(
    (s) => print('data: $s'),
    onError: (Object e) => print('error: $e'),
    onDone: () => print('done'),
  );
  print('listening, hasListener=${controller.hasListener}');
  await controller.done;
}

Output:

hasListener=false
listening, hasListener=true
data: hello
data: world
error: FormatException: bad input
data: again
done

A single-subscription controller buffers everything added before the listener arrives, and also while the subscription is paused. controller.done (also returned by close()) completes once the done event has been delivered.

addStream forwards every event of another stream into the controller. Adding after close() is an error:

import 'dart:async';

Future<void> main() async {
  final c = StreamController<int>();
  c.stream.listen((n) => print('got $n'), onDone: () => print('done'));

  // addStream pipes another stream in; no add() allowed until it finishes
  await c.addStream(Stream.fromIterable([1, 2, 3]));
  c.sink.add(4);
  await c.close(); // completes once the listener has received 'done'
  print('isClosed=${c.isClosed}');

  try {
    c.add(5);
  } on StateError catch (e) {
    print(e);
  }
}

Output:

got 1
got 2
got 3
got 4
done
isClosed=true
Bad state: Cannot add event after closing

Producing events only while someone listens

The constructor callbacks onListen, onPause, onResume and onCancel let a controller start its work lazily and stop it when nobody wants the events. This is the pattern for wrapping callback-based or timer-based APIs:

import 'dart:async';

/// Emits a counter every [interval], but only while someone listens.
Stream<int> counter(Duration interval) {
  late final StreamController<int> controller;
  Timer? timer;
  var n = 0;

  void start() {
    print('  [start timer]');
    timer = Timer.periodic(interval, (_) => controller.add(n++));
  }

  void stop() {
    print('  [stop timer]');
    timer?.cancel();
    timer = null;
  }

  controller = StreamController<int>(
    onListen: start,
    onPause: stop,
    onResume: start,
    onCancel: stop,
  );
  return controller.stream;
}

Future<void> main() async {
  final stream = counter(const Duration(milliseconds: 20));
  print('created, nothing running yet');

  await for (final n in stream) {
    print('got $n');
    if (n == 1) {
      // await for pauses the subscription while the body awaits
      await Future<void>.delayed(const Duration(milliseconds: 50));
    }
    if (n == 3) break;
  }
  print('loop exited');
}

Output:

created, nothing running yet
  [start timer]
got 0
got 1
  [stop timer]
  [start timer]
got 2
got 3
  [stop timer]
loop exited

The timer doesn't exist until await for starts listening, stops while the loop body is awaiting (the subscription is paused), and is cancelled when break cancels the subscription. An async* generator gives you this behaviour for free; reach for StreamController when events come from callbacks you don't control. Converting callbacks to Futures shows the one-shot version of this idea with Completer.

A common design is to keep the controller private and expose only the stream, so callers can listen but can't add events or close it. The thermostat in the next section does that.

Broadcast streams

StreamController.broadcast() creates a stream that any number of listeners can subscribe to:

import 'dart:async';

class Thermostat {
  final _changes = StreamController<double>.broadcast();
  double _temp = 20;

  /// Listeners get only the readings that happen after they subscribe.
  Stream<double> get changes => _changes.stream;

  set temperature(double value) {
    if (value == _temp) return;
    _temp = value;
    _changes.add(value);
  }

  Future<void> dispose() => _changes.close();
}

Future<void> main() async {
  final t = Thermostat();
  t.temperature = 21; // nobody listens: this event is dropped

  final subA = t.changes.listen((v) => print('A: $v'));
  t.changes.where((v) => v > 22).listen((v) => print('B (hot): $v'));
  print('isBroadcast=${t.changes.isBroadcast}');

  t.temperature = 22;
  t.temperature = 23.5;
  await Future<void>.delayed(Duration.zero);

  await subA.cancel();
  t.temperature = 25;
  await t.dispose();

  // a single-subscription stream can be listened to only once
  final single = Stream.periodic(const Duration(seconds: 1)).take(2);
  final first = single.listen((_) {});
  try {
    single.listen((_) {});
  } on StateError catch (e) {
    print(e);
  }
  await first.cancel();

  // asBroadcastStream shares one underlying subscription
  final shared = Stream.periodic(
    const Duration(milliseconds: 10),
    (i) => i + 1,
  ).take(3).asBroadcastStream();
  final r = await Future.wait([
    shared.toList(),
    shared.map((n) => n * n).toList(),
  ]);
  print(r);
}

Output:

isBroadcast=true
A: 22.0
A: 23.5
B (hot): 23.5
B (hot): 25.0
Bad state: Stream has already been listened to.
[[1, 2, 3], [1, 4, 9]]

Differences from single-subscription streams:

asBroadcastStream() wraps a single-subscription stream so several listeners share one underlying subscription. Here both toList calls got the same three ticks.

Assume a stream is single-subscription unless its documentation says otherwise: listening twice throws Bad state: Stream has already been listened to. A few streams are more lenient (in Dart 3.13 Stream.fromIterable and Stream.empty can be listened to repeatedly, while Stream.value, Stream.fromFuture and Stream.periodic can't), but don't rely on that in code that accepts an arbitrary Stream. Common pitfalls shows the error in a real program.

Stream.multi

Stream.multi creates a stream where each listener gets its own fresh controller. It behaves like a single-subscription stream that can be listened to many times, each time starting from scratch:

import 'dart:async';

Future<void> main() async {
  // Stream.multi: every listener gets its own controller,
  // like a single-subscription stream that can be listened to many times
  var listenCount = 0;
  final replay = Stream<String>.multi((c) {
    final id = ++listenCount;
    c.add('hello listener $id');
    c.add('bye listener $id');
    c.close();
  });
  print(await replay.toList());
  print(await replay.toList());
  print('isBroadcast=${replay.isBroadcast}');
}

Output:

[hello listener 1, bye listener 1]
[hello listener 2, bye listener 2]
isBroadcast=false

Stream transformers and reading files

stream.transform(transformer) applies a StreamTransformer<S, T>, a reusable object that turns a Stream<S> into a Stream<T>. The converters in dart:convert are transformers, which is how you decode bytes from a file or socket into lines. StreamTransformer.fromHandlers makes your own from a few callbacks:

import 'dart:async';
import 'dart:convert';
import 'dart:io';

/// Drops blank lines and lines starting with '#'.
final skipComments = StreamTransformer<String, String>.fromHandlers(
  handleData: (line, sink) {
    final t = line.trim();
    if (t.isNotEmpty && !t.startsWith('#')) sink.add(t);
  },
);

/// Parses "key=value" lines; bad lines become error events.
final parseKeyValue =
    StreamTransformer<String, MapEntry<String, String>>.fromHandlers(
      handleData: (line, sink) {
        final i = line.indexOf('=');
        if (i <= 0) {
          sink.addError(FormatException('missing "="', line));
        } else {
          sink.add(MapEntry(line.substring(0, i), line.substring(i + 1)));
        }
      },
    );

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('streams');
  final file = File('${dir.path}/app.conf');
  await file.writeAsString(
    '# settings\nhost=example.com\n\nport=8443\noops\nuser=zoë\n',
  );

  final config = <String, String>{};
  await file
      .openRead() // Stream<List<int>> of byte chunks
      .transform(utf8.decoder) // Stream<String> of text chunks
      .transform(const LineSplitter()) // Stream<String> of lines
      .transform(skipComments)
      .transform(parseKeyValue)
      .handleError(
        (Object e) => print('skipped: ${(e as FormatException).source}'),
      )
      .forEach((e) => config[e.key] = e.value);
  print(config);

  await dir.delete(recursive: true);
}

Output:

skipped: oops
{host: example.com, port: 8443, user: zoë}

File.openRead() returns a Stream<List<int>> of byte chunks, so the file is never fully loaded into memory. utf8.decoder correctly handles a multi-byte character such as ë that is split across two chunks, and LineSplitter handles lines split across chunks as well as \r\n line endings. That's why you should decode with these transformers rather than calling utf8.decode on each chunk yourself. For small files, File.readAsLines() is simpler.

fromHandlers also accepts handleError and handleDone, for transformers that need to react to errors or flush buffered state at the end.

A stateful transformer: debounce

For transformations that keep timers or other state, create an output StreamController that listens to the source in onListen and forwards pause, resume and cancel. Written as an extension method, it chains like the built-in methods:

import 'dart:async';

extension Debounce<T> on Stream<T> {
  /// Emits a value only after [quiet] has passed without a newer one.
  Stream<T> debounce(Duration quiet) {
    late final StreamController<T> out;
    StreamSubscription<T>? sub;
    Timer? timer;
    late T pending;

    out = StreamController<T>(
      onListen: () {
        sub = listen(
          (value) {
            pending = value;
            timer?.cancel();
            timer = Timer(quiet, () => out.add(value));
          },
          onError: out.addError,
          onDone: () {
            if (timer?.isActive ?? false) {
              timer!.cancel();
              out.add(pending); // flush the last value
            }
            out.close();
          },
        );
      },
      onPause: () => sub?.pause(),
      onResume: () => sub?.resume(),
      onCancel: () {
        timer?.cancel();
        return sub?.cancel();
      },
    );
    return out.stream;
  }
}

/// Simulates typing: each (delayMs, text) pair is one keystroke.
Stream<String> keystrokes(List<(int, String)> events) async* {
  for (final (ms, text) in events) {
    await Future<void>.delayed(Duration(milliseconds: ms));
    yield text;
  }
}

Future<void> main() async {
  final typed = keystrokes([
    (0, 'd'), (30, 'da'), (30, 'dar'), (30, 'dart'), // fast typing
    (200, 'dart s'), (30, 'dart st'), // pause, then more
  ]);
  await for (final query in typed.debounce(const Duration(milliseconds: 100))) {
    print('search for "$query"');
  }
}

Output:

search for "dart"
search for "dart st"

Only values followed by 100 ms of silence are emitted. The same structure works for throttling, buffering by time or merging streams. Stateful transformations that don't need timers are usually shorter as an async* function with await for, as shown in Sync and async generators. For production code, package:stream_transform provides debounce, throttle, merge, combineLatest, switchMap and more, and package:async has StreamGroup, StreamQueue and StreamSplitter.

Errors and timeouts

Error events are part of the stream, and the way you consume it decides what they do:

import 'dart:async';

Stream<int> flaky() {
  final c = StreamController<int>();
  c
    ..add(1)
    ..addError(Exception('sensor glitch'))
    ..add(2)
    ..addError(ArgumentError('bad value'))
    ..add(3)
    ..close();
  return c.stream;
}

Future<void> main() async {
  // 1. await for stops at the first error
  try {
    await for (final n in flaky()) {
      print('await for: $n');
    }
  } catch (e) {
    print('await for stopped: $e');
  }

  // 2. listen keeps going after errors (cancelOnError defaults to false)
  final done = Completer<void>();
  flaky().listen(
    (n) => print('listen: $n'),
    onError: (Object e) => print('listen error: $e'),
    onDone: done.complete,
  );
  await done.future;

  // 3. handleError removes matching errors from the stream
  final cleaned = flaky().handleError(
    (Object e) => print('ignored: $e'),
    test: (e) => e is Exception,
  );
  try {
    print(await cleaned.toList());
  } on ArgumentError catch (e) {
    print('not handled: ${e.message}');
  }

  // 4. timeout: error (or fallback) if the gap between events is too long
  Stream<int> slowTicks() =>
      Stream.periodic(const Duration(milliseconds: 250), (i) => i);
  try {
    await slowTicks().timeout(const Duration(milliseconds: 100)).first;
  } on TimeoutException catch (e) {
    print('timeout: ${e.message}');
  }
  final withFallback = slowTicks().timeout(
    const Duration(milliseconds: 150),
    onTimeout: (sink) => sink.add(-1),
  );
  print(await withFallback.take(6).toList());
}

Output:

await for: 1
await for stopped: Exception: sensor glitch
listen: 1
listen error: Exception: sensor glitch
listen: 2
listen error: Invalid argument(s): bad value
listen: 3
ignored: Exception: sensor glitch
not handled: bad value
timeout: No stream event
[-1, 0, -1, 1, -1, 2]

Note that slowTicks is a function. A Stream.periodic stored in a variable could be listened to only once, so the second timeout call would fail with "Stream has already been listened to".

Pulling events with StreamIterator

Sometimes the consumer, not the stream, should drive the pace, for example when parsing a protocol token by token. StreamIterator turns a stream into an async iterator with moveNext() and current, mirroring the synchronous Iterator:

import 'dart:async';

Stream<String> tokens() =>
    Stream.fromIterable(['BEGIN', 'name', 'Ada', 'age', '36', 'END', 'extra']);

Future<void> main() async {
  final it = StreamIterator(tokens());

  Future<String> next() async {
    if (!await it.moveNext()) throw StateError('unexpected end');
    return it.current;
  }

  if (await next() != 'BEGIN') throw FormatException('expected BEGIN');
  final record = <String, String>{};
  while (true) {
    final key = await next();
    if (key == 'END') break;
    record[key] = await next();
  }
  print(record);
  await it.cancel(); // we don't need 'extra'
}

Output:

{name: Ada, age: 36}

Each await it.moveNext() returns true with the next event in current, or false at the end. If you stop early, call cancel() so the underlying subscription is released. StreamQueue from package:async is a richer version with next, take(n), lookAhead and skip.

Common mistakes

Not closing a controller is the most common stream bug. await for waits for a done event that never comes. If nothing else keeps the program alive, the Dart VM simply exits when the event loop is empty, so the code after the loop silently never runs:

import 'dart:async';

Future<void> main() async {
  final c = StreamController<int>();
  c.add(1);
  c.add(2);
  // forgot: c.close();

  await for (final n in c.stream) {
    print('got $n');
  }
  print('after loop'); // never printed
}

Output:

got 1
got 2

The process exited with code 0 without printing after loop. Always close() controllers when the producer is finished, typically in a finally block or a dispose() method.

Other pitfalls:

Summary

See also Async and Await, Isolates (whose ports are streams), WebSockets and TCP sockets for streams in real network code.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents