Sub topic 1
Futures and Streams: One Value Versus Many Over Time
Prerequisites
This chapter assumes you know Dart's async and await keywords, can write a StatefulWidget, and understand setState, initState, and dispose.
Futures and Streams
A Future<T> represents one value that arrives later. It completes once, with either a value or an error. A Stream<T> represents a sequence of values over time. It can emit zero, one, or many values, then close or fail.
Use a Future for a single request, such as loading a user profile. Use a Stream for repeated updates, such as chat messages or sensor readings.
How Flutter Rebuilds UI from State
Flutter builds the screen by calling build. It calls build again whenever the state changes, and the widget tree updates to match the new result. Async widgets rely on this model. When a Future or Stream produces new information, the builder runs again and draws the screen for that information.
Reading an AsyncSnapshot and its ConnectionState
FutureBuilder and StreamBuilder pass an AsyncSnapshot to the builder function. The snapshot describes the current state:
| Property | Meaning |
|---|---|
| `connectionState` | Where the async work stands: `none`, `waiting`, `active`, or `done` |
| `hasData` | True when `data` holds a non-null value |
| `hasError` | True when `error` holds a failure |
A Future moves from waiting to done. A Stream uses active while events arrive.
Rendering a Future with FutureBuilder
FutureBuilder connects a Future to the widget tree. Check for an error first, then for data, and show a spinner otherwise:
FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
if (snapshot.hasData) return Text('Hello, ${snapshot.data}');
return const CircularProgressIndicator();
},
)The _name future must be created once, outside build, and stored in the State object. Creating it inside build starts a new request on every rebuild.
Exercise
Why should the Future passed to FutureBuilder be stored in State rather than created inside build?
Show answer
Each rebuild calls build again. If build creates the Future, FutureBuilder receives a new Future each time, which restarts the request and resets the snapshot to the waiting state.