Sub topic 1
Futures and Streams: One Value Versus Many Over Time
Flutter widgets draw themselves from data. Some of that data is not available when build runs. A network response arrives later, a database query finishes later, and a sensor keeps producing readings. Dart models these cases with two types: Future<T> for one value that arrives later, and Stream<T> for zero or more values that arrive over time. Every later chapter in this tutorial depends on this distinction, because FutureBuilder consumes a Future and StreamBuilder consumes a Stream.
This chapter covers only the Dart side. It shows how each type delivers its results, how errors travel, and which behaviors will matter when you connect them to widgets.
Prerequisites
This chapter assumes you already know:
- Dart basics:
async,await, and how to declare aFuture<T>function. - Flutter basics: the difference between
StatelessWidgetandStatefulWidget, and what thebuildmethod does. setStateand the widget lifecycle methodsinitStateanddispose.
The examples here are plain Dart programs. You can run each one with dart run file.dart and no Flutter project is needed.
A Future is one result, delivered later
A Future<T> represents a single result that is not ready yet. It is always in one of three states:
- Uncompleted: the work is still running.
- Completed with a value: the work finished and produced a
T. - Completed with an error: the work failed and produced an exception and a stack trace.
A Future leaves the uncompleted state once and never changes again. It cannot produce a second value, and it cannot go back to waiting.
Future<String> fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
Future<void> main() async {
print('before');
final name = await fetchName();
print('got $name');
}This prints before, then waits about a second, then prints got Ada. The await keyword pauses main until the Future completes. It does not block the program's other work.
Handling Future errors
A failed Future rethrows its error at the await. You handle it with an ordinary try/catch.
Future<int> parseAge(String input) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
final age = int.tryParse(input);
if (age == null) {
throw FormatException('Not a number', input);
}
return age;
}
Future<void> main() async {
try {
print(await parseAge('42'));
print(await parseAge('abc'));
} on FormatException catch (e) {
print('Failed: ${e.message}');
}
}The output is 42 and then Failed: Not a number. If nobody awaits a failed Future or attaches an error handler, Dart reports the error as unhandled. A builder widget will later play the role of that handler, and it will present the error as data instead of throwing it.
A Future is already running when you hold it
A Future is not a recipe that runs later. Calling an async function starts the work immediately. The function body runs synchronously until its first await, and the Future you get back is a handle to work already in progress.
Future<void> work() async {
print('inside work');
await Future<void>.delayed(const Duration(milliseconds: 100));
}
Future<void> main() async {
print('calling');
final future = work();
print('called, not awaited');
await future;
print('done');
}The output order is calling, inside work, called, not awaited, done. inside work appears before called, not awaited because the body of work ran during the call.
This is the root of the most common Flutter bug in this area. If you call an async function inside build, you start new work every time build runs. A later chapter covers that bug in detail. For now, remember that holding a Future does not mean it has not started.
A Stream is many results over time
A Stream<T> is a sequence of asynchronous events. A listener can receive three kinds of event:
- Data events: a value of type
T. There can be any number of these. - Error events: an error and a stack trace. There can be any number of these too.
- A done event: the stream is finished. After it, nothing more is delivered.
A stream may emit nothing, emit one value, emit thousands of values, or never finish. Typical sources are periodic timers, user input, web sockets, file reads, and database change feeds.
The simplest way to write your own stream is an async* function. It uses yield to emit a value and returns when the stream is done.
Stream<int> countDown(int from) async* {
for (var i = from; i > 0; i--) {
await Future<void>.delayed(const Duration(milliseconds: 200));
yield i;
}
}
Future<void> main() async {
await for (final n in countDown(3)) {
print(n);
}
print('done');
}The program prints 3, 2, 1, and done, about 200 ms apart. The await for loop is to a Stream what await is to a Future. It handles each data event in turn and exits when the stream sends its done event.
Listening with callbacks
Widgets do not use await for. They subscribe with listen, which takes one callback per event type and returns a StreamSubscription.
Stream<int> countDown(int from) async* {
for (var i = from; i > 0; i--) {
await Future<void>.delayed(const Duration(milliseconds: 200));
yield i;
}
}
void main() {
final subscription = countDown(3).listen(
(n) => print('data $n'),
onError: (Object e) => print('error $e'),
onDone: () => print('done'),
);
// Calling subscription.cancel() would stop delivery early.
print('subscribed: ${subscription.isPaused ? 'paused' : 'active'}');
}The subscription is the connection between the stream and your code. Calling cancel() on it stops delivery and releases the resources the stream holds. Forgetting to cancel a subscription is a classic leak, and it is the reason StreamBuilder exists: it subscribes and cancels for you.
Errors do not always end a stream
On a Future, an error is the final outcome. On a Stream, an error is one event among others. A stream built with a StreamController can report an error and then keep sending data.
import 'dart:async';
Future<void> main() async {
final controller = StreamController<int>();
controller.stream.listen(
(v) => print('data $v'),
onError: (Object e) => print('error $e'),
onDone: () => print('done'),
);
controller.add(1);
controller.addError(Exception('boom'));
controller.add(2);
await controller.close();
}The output is data 1, error Exception: boom, data 2, done. A listener receives events in the order they were added.
An async* generator behaves differently. If the generator body throws, the error is delivered and then the stream closes. A stream's behavior after an error depends on how it was built. You can also pass cancelOnError: true to listen to cancel the subscription at the first error.
Two kinds of stream
Streams come in two kinds, and the difference affects widgets.
A single-subscription stream allows exactly one listener over its lifetime. Events produced before anyone listens are buffered and delivered once a listener arrives. A second listen call throws a StateError. Streams made with StreamController<T>() and async* functions are of this kind.
A broadcast stream allows any number of listeners at once. It does not buffer for absent listeners, so events sent while nobody is listening are lost.
import 'dart:async';
Future<void> main() async {
final controller = StreamController<int>.broadcast();
controller.add(1); // No listener yet, so this event is dropped.
controller.stream.listen((v) => print('A $v'));
controller.stream.listen((v) => print('B $v'));
controller.add(2);
await controller.close();
}This prints A 2 and B 2. The value 1 is never seen. The same program with a plain StreamController<int>() would throw on the second listen, with the message Bad state: Stream has already been listened to.
Streams also differ from Futures in when they start working. An async* generator is lazy: its body does not begin until someone listens. A Future is eager, as shown above. A later chapter covers the lifecycle of controllers in full, including when to call close.
Side by side
| Property | `Future<T>` | `Stream<T>` |
|---|---|---|
| Number of values | Exactly one, or one error | Zero or more data events, plus optional errors |
| Completion | Completes once, then never changes | Sends a done event, or may never finish |
| Start | Eager: work begins when you call the function | Depends on the source. An `async*` stream starts on listen |
| Consume with | `await`, `then` | `await for`, `listen` |
| After an error | The Future is finished | Often continues. Depends on how the stream was built |
| Cleanup | Nothing to cancel | Cancel the `StreamSubscription` |
| Typical use | One HTTP request, one file read | Clock ticks, socket messages, database updates |
The diagram shows the shape of each type over time. The Future produces one outcome and ends. The Stream produces a series of events and ends only if its source closes.
Why this matters for widgets
A Flutter widget must produce something to draw in every frame. A Future or Stream has no value yet at the moment build first runs, so the widget needs an answer to the question "what do I draw now?" The builder widgets answer it by taking the current state of the Future or Stream and handing it to your code. The next chapters cover two things in turn: how Flutter rebuilds the UI from state, and the AsyncSnapshot object that describes the current state.
Two rules from this chapter carry forward:
- A Future is already running once you hold it. Where you create it decides how often the work happens.
- A Stream needs a subscription, and a subscription needs to be cancelled. Whether a Stream allows one listener or many decides how you can share it between widgets.
Exercise
You write Future<String> loadTitle() async { print('start'); await Future<void>.delayed(Duration(seconds: 1)); return 'Hi'; }. In main, you call final f = loadTitle(); and never await f. Does start print? Explain what this says about when a Future's work begins.
Show answer
Yes, start prints. An async function runs synchronously up to its first await, so the call itself starts the work. The Future is a handle to work already in progress. It is not a description of work that starts later. The same holds when a Future is created inside a widget's build method: every call to build starts the work again.
Exercise
A StreamController<int>() has no .broadcast(). Your code calls controller.stream.listen(...) twice. What happens, and what would happen to an event added before the first listener subscribed if you used StreamController<int>.broadcast() instead?
Show answer
With a single-subscription controller, the second listen call throws a StateError with the message "Bad state: Stream has already been listened to." With a broadcast controller, the second listener is allowed. Events added while no one is listening are dropped, so the event added before the first listener subscribed would never be delivered. A single-subscription stream would have buffered that event until a listener arrived.