Dart Streams
A Future delivers one value later. A Stream delivers a sequence of values over time: chat messages arriving, the position of a GPS sensor, the text a user types, download progress. In Flutter, the StreamBuilder widget redraws the UI each time a stream emits.
| Single value | Many values | |
|---|---|---|
| Synchronous | T |
Iterable<T> |
| Asynchronous | Future<T> |
Stream<T> |
Listening with await for
Inside an async function you can loop over a stream with await for. The loop body runs for every event and the loop ends when the stream is done.
Stream<int> countdown(int from) async* {
for (var i = from; i > 0; i--) {
await Future.delayed(const Duration(milliseconds: 10));
yield i;
}
}
Future<void> main() async {
await for (final n in countdown(3)) {
print('T-minus $n');
}
print('Liftoff!');
}T-minus 3
T-minus 2
T-minus 1
Liftoff!
async* marks a generator function that returns a Stream; each yield emits one value. (The synchronous counterpart, sync*, produces an Iterable.)
Creating streams
| Constructor | Produces |
|---|---|
Stream.fromIterable([1, 2, 3]) |
Each list item as an event |
Stream.value(x) |
A single event |
Stream.periodic(duration, f) |
An event every duration |
Stream.fromFuture(f) |
The future's result as one event |
async* function |
Whatever you yield |
StreamController |
Events you add manually |
Transforming streams
Streams have methods similar to lists — map, where, take, skip, expand — which return new streams. There are also aggregate methods such as toList, first and fold that return futures.
Future<void> main() async {
final readings = Stream.fromIterable([18, 21, 35, 19, 40, 22]);
final alerts = readings
.where((t) => t > 30)
.map((t) => 'High temperature: $t°C');
await for (final message in alerts) {
print(message);
}
final total = await Stream.fromIterable([1, 2, 3, 4]).fold(0, (a, b) => a + b);
print('Sum: $total');
final firstTwo = await Stream.fromIterable(['a', 'b', 'c']).take(2).toList();
print(firstTwo);
}High temperature: 35°C
High temperature: 40°C
Sum: 10
[a, b]
listen and subscriptions
await for is convenient, but it pauses the surrounding function. The lower-level listen method registers callbacks and returns a StreamSubscription you can pause, resume or cancel.
import 'dart:async';
Future<void> main() async {
final ticks = Stream.periodic(const Duration(milliseconds: 20), (i) => i + 1);
final done = Completer<void>();
late StreamSubscription<int> sub;
sub = ticks.listen((tick) {
print('tick $tick');
if (tick == 3) {
sub.cancel();
done.complete();
}
});
await done.future;
print('Subscription cancelled');
}tick 1
tick 2
tick 3
Subscription cancelled
Tip: In Flutter, always cancel subscriptions in your
State.dispose()method — otherwise the stream keeps calling a widget that no longer exists.StreamBuilderdoes this for you.
StreamController
A StreamController lets you create a stream and push events into it yourself — useful for building simple app-wide event buses or state containers.
import 'dart:async';
class CartBloc {
final _controller = StreamController<int>();
int _count = 0;
Stream<int> get count => _controller.stream;
void addItem() => _controller.add(++_count);
void close() => _controller.close();
}
Future<void> main() async {
final cart = CartBloc();
final printing = cart.count.forEach((n) => print('Cart badge: $n'));
cart.addItem();
cart.addItem();
cart.addItem();
cart.close();
await printing;
print('Cart stream closed');
}Cart badge: 1
Cart badge: 2
Cart badge: 3
Cart stream closed
Single-subscription vs broadcast
By default a stream allows one listener (a single-subscription stream), which suits data that must arrive in full, like a file. A broadcast stream allows any number of listeners, which suits events like button clicks.
import 'dart:async';
Future<void> main() async {
final controller = StreamController<String>.broadcast();
controller.stream.listen((e) => print('Logger saw: $e'));
controller.stream.listen((e) => print('UI saw: $e'));
controller.add('login');
controller.add('logout');
await controller.close();
}Logger saw: login
UI saw: login
Logger saw: logout
UI saw: logout
Calling listen twice on a single-subscription stream throws a StateError; convert with asBroadcastStream() if you need more listeners.
Test yourself
What keyword makes a function return a Stream that you fill with yield?
- async
- sync*
- async*
- stream
Which type best represents a series of chat messages arriving over time?
- Future<String>
- List<String>
- Stream<String>
- Iterable<String>
What happens if you call listen twice on a single-subscription stream?
- Both listeners get events
- Only the second gets events
- It throws a StateError
- Events are split between them