Dart Streams
A stream is a sequence of values that arrive over time. Code subscribes with listen and receives each value as it arrives.
Listening to a stream
The listen function prints each value as it arrives. onDone prints done after the last value.
import 'dart:async';
Future<void> main() async {
var stream = Stream.fromIterable([10, 20, 30]);
stream.listen((v) => print('got $v'), onDone: () => print('done'));
}Listening twice to the same stream
The second listen starts inside onDone, after the first listen finishes. Each listen receives the full sequence from the start.
import 'dart:async';
Future<void> main() async {
var stream = Stream.fromIterable([7, 8]);
stream.listen(
(v) => print('first $v'),
onDone: () {
stream.listen((v) => print('second $v'));
},
);
}A stream from a future
Stream.fromFuture waits for the future and delivers its single value. The listen function prints that value as a result line.
import 'dart:async';
Future<void> main() async {
var stream = Stream.fromFuture(Future.value(99));
stream.listen((v) => print('result: $v'));
}Example
import 'dart:async';
Future<void> main() async {
var total = 0;
var stream = Stream.fromIterable([2, 4, 6]);
stream.listen(
(v) {
total += v;
print('added $v');
},
onDone: () => print('total $total'),
);
}Key points
- A stream delivers its values one by one, rather than all at once.
- listen subscribes to a stream and runs its function once for each value.
- A subscription delivers the data first and the done signal last.
- The onDone callback runs once, after the last value, when the stream is finished.
- Stream.fromIterable builds a stream from an iterable such as a list.
- A stream built by Stream.fromIterable can be listened to again, and the new listener receives the full sequence again.
- Stream.fromFuture builds a stream that delivers the value of one future and then finishes.
In this example, the listen function adds each value to total and prints the value it added. When the stream finishes, onDone prints the total 12.
Note
Stream lives in the dart:async library, so a stream program starts with that import.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does listen do on a stream?