Sub topic 3
Reading an AsyncSnapshot and its ConnectionState
This chapter assumes you know Dart's async, await, and Future, and the basics of StatefulWidget, setState, initState, and dispose. You should also know that Flutter calls build again whenever state changes. We won't build a full screen yet. The goal is to learn what a builder hands you, so that the FutureBuilder and StreamBuilder chapters that follow are easy to read.
Why a snapshot exists
build is a synchronous function. It must return a widget right now, but a Future or Stream produces its values later. Flutter bridges that gap with a plain, immutable value object, AsyncSnapshot<T>. It describes what is known about the async source at one moment.
FutureBuilder and StreamBuilder subscribe to the source for you. Each time the source changes, they store a new snapshot and rebuild. Your builder callback receives that snapshot and turns it into widgets:
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
// Look at the snapshot, return a widget.
}The builder holds no state of its own. If you can read the snapshot correctly, you can render any async source.
The fields of AsyncSnapshot
A snapshot has four main pieces of information.
| Member | Type | Meaning |
|---|---|---|
| `connectionState` | `ConnectionState` | How far along the subscription is: `none`, `waiting`, `active`, or `done`. |
| `data` | `T?` | The most recent value, or `null` if there is none. |
| `error` | `Object?` | The most recent error, or `null`. |
| `stackTrace` | `StackTrace?` | The stack trace that came with the error, if any. |
It also has convenience getters:
hasDatais true whendatais notnull.hasErroris true whenerroris notnull.requireDatareturnsdataas a non-nullableT. If there is no data but there is an error, it rethrows that error. If there is neither, it throws aStateError.
Two points are easy to miss. First, data and error are not mutually exclusive in every situation, as a later section shows. Second, hasData tests for non-null, so a Future<String?> that completes with null gives hasData == false even though it finished successfully. Check connectionState as well, instead of treating hasData as "finished."
The four ConnectionState values
ConnectionState is an enum with four values. The same names are used for futures and streams, but they mean slightly different things.
| Value | With a Future | With a Stream |
|---|---|---|
| `none` | `future` is `null`, so nothing is being tracked. | `stream` is `null`, so nothing is being tracked. |
| `waiting` | Subscribed, not completed yet. | Subscribed, no event has arrived yet. |
| `active` | Never used. | At least one event has arrived and the stream is still open. |
| `done` | The future completed with a value or an error. | The stream closed. |
The most important consequence is that a Future never reports active. It goes straight from waiting to done. A stream moves through waiting, then active for as long as events keep arriving, then done when it closes.
A none state is rare in practice. You see it when you pass a null future or stream, which is legal because the parameter is nullable. This is useful when the source is not ready yet, for example while you wait for a user to log in.
Data and error together
For a Future, you get exactly one result. The snapshot ends in done with either data or error.
For a Stream, the snapshot always reflects the latest event. A data event produces a snapshot with that data and no error. An error event produces a snapshot with an error. A stream can emit an error and then keep emitting data, because Dart streams do not have to stop after an error unless the source cancels on error. The builder will therefore show the error snapshot for a moment and then a data snapshot, and connectionState stays active throughout. An error does not mean the stream is finished.
The other combination to watch for is a source being replaced. If a FutureBuilder gets a new Future in a rebuild, it moves back to waiting. It keeps the previous data in the snapshot until the new result arrives. So you can briefly see connectionState == waiting together with hasData == true. The next chapters use this to explain flicker and stale values. For now, remember that hasData does not mean the data is current.
Reading a snapshot in the right order
Because several fields can be set at once, the order of your checks decides what the user sees. A reliable order is:
- If
hasError, show the error. An error is the most specific fact you have. - Otherwise, if
hasData, show the data. - Otherwise, show a loading state, because the snapshot is
noneorwaiting.
Checking connectionState first is also valid, and it is clearer when you need to tell "loading" from "finished with nothing":
Widget describe(AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const Text('No source yet');
case ConnectionState.waiting:
return const CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Value: ${snapshot.data}');
}
}A switch over an enum has to cover every case, so the compiler warns you if you forget active. Many Future-only screens never see active, but grouping it with done is harmless and keeps the same function reusable for streams.
A runnable inspector
Reading about the states is useful, but seeing them is better. This app shows every snapshot field for a future that waits one second and then succeeds or fails. Press the button to switch between success and failure. Each press creates a new Future in setState, which is the correct place to create one. The next chapters explain why.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: SnapshotInspector()));
class SnapshotInspector extends StatefulWidget {
const SnapshotInspector({super.key});
@override
State<SnapshotInspector> createState() => _SnapshotInspectorState();
}
class _SnapshotInspectorState extends State<SnapshotInspector> {
bool _shouldFail = false;
late Future<String> _future = _load();
Future<String> _load() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (_shouldFail) {
throw StateError('Server said no');
}
return 'Ada';
}
void _reload({required bool fail}) {
setState(() {
_shouldFail = fail;
_future = _load();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('AsyncSnapshot inspector')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FutureBuilder<String>(
future: _future,
builder: (context, snapshot) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('connectionState: ${snapshot.connectionState}'),
Text('hasData: ${snapshot.hasData}'),
Text('data: ${snapshot.data}'),
Text('hasError: ${snapshot.hasError}'),
Text('error: ${snapshot.error}'),
],
);
},
),
const SizedBox(height: 24),
Row(
children: [
ElevatedButton(
onPressed: () => _reload(fail: false),
child: const Text('Load OK'),
),
const SizedBox(width: 12),
ElevatedButton(
onPressed: () => _reload(fail: true),
child: const Text('Load failing'),
),
],
),
],
),
),
);
}
}When you run it, watch the text lines. At first you see connectionState: ConnectionState.waiting, hasData: false, and hasError: false. After one second the state becomes done with data: Ada. Press "Load failing" and the state returns to waiting. The old Ada may still appear in the data line while the new request is running, which is the behavior described earlier. After one more second you get done, hasError: true, and the error text. Because the state is done and hasData is false, a rule that looks only at hasData would never tell you about the failure.
Building snapshots by hand
You do not always need a real Future to get a snapshot. AsyncSnapshot has named constructors that create one directly:
AsyncSnapshot<T>.nothing()creates anonesnapshot.AsyncSnapshot<T>.waiting()creates awaitingsnapshot.AsyncSnapshot<T>.withData(state, data)creates a snapshot that carries data.AsyncSnapshot<T>.withError(state, error, [stackTrace])creates a snapshot that carries an error.
These matter most because they let you test the rendering logic in isolation. If you move the switch from the earlier example into a small widget or a function that takes an AsyncSnapshot, you can check every state without timers:
import 'package:flutter/material.dart';
Widget describe(AsyncSnapshot<String> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
return Text('Value: ${snapshot.data}');
}
return const CircularProgressIndicator();
}
void main() {
final samples = <AsyncSnapshot<String>>[
const AsyncSnapshot<String>.nothing(),
const AsyncSnapshot<String>.waiting(),
const AsyncSnapshot<String>.withData(ConnectionState.done, 'Ada'),
AsyncSnapshot<String>.withError(ConnectionState.done, StateError('boom')),
];
for (final s in samples) {
print('${s.connectionState}: hasData=${s.hasData} hasError=${s.hasError}');
}
}This prints four lines, one per snapshot, and needs only the Flutter SDK. Later chapters on testing show how to wrap this idea in widget tests.
Common mistakes
- Treating
waitingas "no data yet." After a source is replaced,waitingcan come with old data. Decide on purpose whether to show the old data or hide it. - Forgetting that streams use
active. A check likeconnectionState == ConnectionState.donenever becomes true for a stream that stays open, so aStreamBuilderguarded this way shows its loading state forever. - Ignoring
none. If your source is nullable and can benull,noneis a real state. Decide what the user sees: a prompt, an empty box, or a disabled control. - Using
snapshot.data!without checking. This crashes duringwaitingand after errors. UsehasData, or callrequireDataonly after you have confirmedhasData. - Hiding errors. Showing only a spinner when
dataisnullleaves the user stuck on failure. Always givehasErrorits own branch.
What comes next
You now know the vocabulary. A snapshot tells you the connection state, the latest data, and the latest error. The next chapter uses it inside FutureBuilder, where you will build the loading, error, and data screen and see why the Future must not be created inside build.
Exercise
A StreamBuilder<int> shows a spinner forever, even though the stream emits a new number every second. The builder starts with if (snapshot.connectionState != ConnectionState.done) return const CircularProgressIndicator();. What is wrong, and how would you fix it?
Show answer
A stream that stays open reports ConnectionState.active after its first event, and only reaches done when it closes. The periodic stream never closes, so the condition is always true and the spinner never goes away. Fix it by showing the spinner only while connectionState == ConnectionState.waiting (or while !snapshot.hasData, after checking hasError), and render snapshot.data for active and done.
Exercise
A FutureBuilder<String> has a future that fails. Your builder begins with if (!snapshot.hasData) return const CircularProgressIndicator();. What does the user see, and what are the values of connectionState, hasData, and hasError?
Show answer
The user sees the spinner forever. The future has completed, so connectionState is done, but hasData is false because there is no value, and hasError is true. Because the builder checks only hasData, the error is never shown. Check snapshot.hasError first and render the error.