Sub topic 1
Futures and Streams: One Value Versus Many Over Time
Prerequisites
This chapter assumes you know Dart async, await, and Future, along with Flutter's StatelessWidget, StatefulWidget, build, initState, dispose, and setState.
Flutter applications often depend on values that are not available during the first build. A server request, database query, file read, or sensor update may finish later. Dart provides two main abstractions for these values:
- A
Future<T>represents one eventual result of typeT. - A
Stream<T>represents a sequence of values of typeTdelivered over time.
Both are asynchronous. Their delivery patterns differ.
Future: One Eventual Result
A future completes once. It either completes with a value or completes with an error. For example, a request for a user profile normally returns one profile:
Future<String> loadUserName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}You can consume this future with await:
final name = await loadUserName();The await expression pauses the current asynchronous function until the future completes. It does not block Flutter's UI thread. While the operation is pending, Flutter can continue handling input and drawing frames.
A future has a simple lifecycle:
- It is pending.
- It completes with data or an error.
- It stays completed.
A future does not produce a second value. If an operation needs to provide new values repeatedly, use a stream.
Stream: Many Events Over Time
A stream is an asynchronous sequence. It can emit zero, one, or many events. A timer, chat connection, download progress report, or device sensor can produce a stream.
final Stream<int> ticks =
Stream<int>.periodic(const Duration(seconds: 1), (count) => count + 1);This stream emits 1, then 2, then 3, with one second between events. A listener receives each event:
final subscription = ticks.listen((value) {
print('Received $value');
});A stream can also finish or report an error. After a stream emits a done event, it cannot emit more events. Unlike a future, a stream may remain active for an unknown amount of time.
| Abstraction | Values delivered | Typical examples | Completion |
|---|---|---|---|
| `Future<T>` | One | HTTP request, database query | Always completes with data or error |
| `Stream<T>` | Zero or many | Timer, WebSocket, sensor | May finish, fail, or remain active |
The Working Model
Flutter widgets rebuild when their inputs change. An asynchronous operation is not itself a widget, so Flutter needs a way to connect its progress to the widget tree. FutureBuilder and StreamBuilder perform that connection.
The builder widget listens to the asynchronous source and rebuilds its child when the source changes.
The builder does not make the operation synchronous. It observes the operation and exposes its current status to build.
Choosing Between Them
Choose a future when the UI needs one answer:
- Load a product page.
- Submit a form.
- Read saved settings.
- Authenticate a user.
Choose a stream when the UI must react to repeated events:
- Display a countdown.
- Show incoming messages.
- Reflect a live database query.
- Track download progress.
A future can be converted into a stream containing one event, but that does not make it a good choice for repeated updates. Similarly, repeatedly starting futures is usually a poor substitute for a stream because it requires manual scheduling and cancellation.
Common Errors
Do not treat a future as if it already contains its result. The following variable stores the operation, not the completed string:
final Future<String> name = loadUserName();The value becomes available only after completion. In Flutter, later chapters will use FutureBuilder to render the pending, successful, and failed states.
Also consider ownership. A long-lived stream may continue producing events after its widget leaves the tree. The code that creates or subscribes to that stream must cancel or close it at the appropriate lifecycle point. A builder simplifies subscription management, but it does not remove the need to understand who owns the stream.
Exercise
You need to display a server response once and then show live temperature updates every second. Which abstraction should each operation use?
Show answer
Use a Future for the server response because it produces one eventual result. Use a Stream for the temperature updates because it produces repeated values over time.