Dart Streams
A Future delivers one value later. A Stream<T> delivers many values over time: clicks, chat messages, sensor readings, lines of a file, progress updates. A stream emits three kinds of events — data, error and done — and you react to them by listening.
| Single value | Many values | |
|---|---|---|
| Synchronous | T |
Iterable<T> |
| Asynchronous | Future<T> |
Stream<T> |
Creating streams with async*
The easiest way to produce a stream is an async* generator function. It yields values and can await in between:
Stream<String> downloadProgress(int chunks) async* {
for (var i = 1; i <= chunks; i++) {
await Future.delayed(Duration(milliseconds: 10));
yield '${(i / chunks * 100).round()}%';
}
}
Future<void> main() async {
await for (final progress in downloadProgress(4)) {
print('downloaded $progress');
}
print('complete');
}downloaded 25%
downloaded 50%
downloaded 75%
downloaded 100%
complete
await for waits for each event and exits the loop when the stream is done. It only works inside an async function.
Other ways to create streams
| Constructor | Produces |
|---|---|
Stream.value(x) |
One value, then done |
Stream.fromIterable(xs) |
Each element, then done |
Stream.fromFuture(f) |
The future's result |
Stream.periodic(d, (i) => …) |
A value every d (infinite — use take) |
Stream.error(e) |
A single error |
StreamController<T>() |
Push events manually with add, addError, close |
Future<void> main() async {
final fromList = Stream.fromIterable(['a', 'b', 'c']);
print(await fromList.toList());
final ticks = Stream.periodic(Duration(milliseconds: 5), (i) => i * 10).take(4);
await for (final t in ticks) {
print('tick $t');
}
final total = await Stream.fromIterable([3, 4, 5]).reduce((a, b) => a + b);
print('total $total');
}[a, b, c]
tick 0
tick 10
tick 20
tick 30
total 12
Listening with listen
await for is convenient, but it blocks the rest of the function until the stream ends. listen registers callbacks and returns a StreamSubscription, which you can pause, resume or cancel:
import 'dart:async';
Future<void> main() async {
final controller = StreamController<String>();
final sub = controller.stream.listen(
(msg) => print('message: $msg'),
onError: (Object e) => print('error: $e'),
onDone: () => print('stream closed'),
);
controller.add('hello');
controller.add('how are you?');
controller.addError(FormatException('garbled packet'));
controller.add('bye');
await controller.close(); // completes after the done event is delivered
await sub.cancel();
}message: hello
message: how are you?
error: FormatException: garbled packet
message: bye
stream closed
A StreamController is the bridge between imperative code ("something happened — add it") and stream consumers.
Single-subscription vs broadcast
By default a stream is single-subscription: exactly one listener, and events are buffered until someone listens. A broadcast stream allows any number of listeners, but a listener only receives events emitted after it subscribed.
import 'dart:async';
Future<void> main() async {
final single = StreamController<int>();
single.stream.listen((v) => print('first listener: $v'));
try {
single.stream.listen((v) {});
} on StateError catch (e) {
print('second listener: ${e.message}');
}
single.add(1);
await single.close();
final bus = StreamController<String>.broadcast();
bus.stream.listen((e) => print('logger got $e'));
bus.add('login');
await Future.delayed(Duration.zero); // let 'login' be delivered
bus.stream.listen((e) => print('analytics got $e'));
bus.add('purchase');
await bus.close();
}second listener: Stream has already been listened to.
first listener: 1
logger got login
logger got purchase
analytics got purchase
The analytics listener missed login because it subscribed after that event was delivered — broadcast streams don't buffer for latecomers.
Note: A few constructors, such as
Stream.fromIterableandStream.periodic, create streams that may be listened to more than once: each listener simply gets its own fresh run of the events.
Errors in streams
In await for, an error event is thrown at the loop, so wrap it in try/catch. By default an error cancels the await for loop:
Stream<int> readings() async* {
yield 21;
yield 22;
throw StateError('sensor disconnected');
}
Future<void> main() async {
try {
await for (final r in readings()) {
print('reading $r');
}
} on StateError catch (e) {
print('stopped: ${e.message}');
}
}reading 21
reading 22
stopped: sensor disconnected
Tip: Always cancel subscriptions you no longer need (
await sub.cancel()), especially in long-lived objects such as Flutter widgets'disposemethod — otherwise the listener and everything it references stay in memory.
Test yourself
Which keyword turns a function into a stream generator?
- async
- sync*
- async*
- stream
What happens when you call listen twice on a single-subscription stream?
- Both get all events
- The second call throws a StateError
- The first listener is replaced
- Events are split between them
When does an await for loop end normally?
- After the first event
- When the stream emits a done event
- After a timeout
- Never