← → or space · progress saves for Continue on the roadmap
Goal
Use a Future for one eventual value and a Stream for zero or many values over time.
Step 1 - One value
Future<int> once() async => 1;
Future<void> main() async {
print(await once());
}Step 2 - Many values
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
await for (final v in countTo(3)) {
print(v);
}
}Step 3 - Mental model
Future<T>completes once withTor an error.Stream<T>emitsTevents, then may close, or may signal an error.
Good habit
- If callers need partial results or cancellations, lean toward
Streamor pass a callback; if there is exactly one outcome, preferFuture.
Practice tasks
- Rewrite
countTousingStream.periodicandtakeinstead ofasync*. - Name one browser or CLI event that is naturally a stream (keyboard, ticks, socket chunks).