Sub topic 3
Reading an AsyncSnapshot and its ConnectionState
This chapter assumes you know Dart async, await, and Future, plus Flutter StatefulWidget, build, setState, initState, and dispose.
An AsyncSnapshot<T> is a record of the latest asynchronous state that a builder can render. The type parameter T is the value type, such as String or List<User>. FutureBuilder<T> and StreamBuilder<T> pass a snapshot to their builder function whenever the asynchronous source changes.
A snapshot has three important parts:
connectionStatesays how the builder is connected to the asynchronous source.datacontains the latest successful value, if one exists.errorcontains the latest error, if one exists.
Understanding ConnectionState
ConnectionState does not describe whether the operation succeeded. It describes the subscription's relationship with the source.
| State | Meaning | Typical source |
|---|---|---|
| `none` | No asynchronous source is connected | A builder has no `future` or `stream` |
| `waiting` | The source is connected, but no current result is ready | A pending `Future` or a stream before its first event |
| `active` | The source is connected and may deliver more values | A `Stream` that is still producing events |
| `done` | The source finished | A completed `Future` or closed `Stream` |
A Future normally moves from waiting to done. A Stream normally moves from waiting to active, and later to done. A stream can emit several data values while it is active.
The snapshot can contain data or an error independently of the connection state. For example, a stream can be active while its latest event is data. When a future fails, its final snapshot is usually done with hasError == true.
Choosing What to Render
Use the snapshot's convenience properties instead of checking every field manually:
snapshot.hasDatais true whendatais available.snapshot.hasErroris true whenerroris available.snapshot.datareads the value asT?.snapshot.errorreads the error asObject?.
A common rendering order checks the error first, then the successful data, and finally the loading state:
import 'package:flutter/material.dart';
class NameResult extends StatelessWidget {
const NameResult({super.key, required this.snapshot});
final AsyncSnapshot<String> snapshot;
@override
Widget build(BuildContext context) {
if (snapshot.hasError) {
return Text('Could not load the name: ${snapshot.error}');
}
if (snapshot.hasData) {
return Text('Hello, ${snapshot.data}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return const Text('No name available');
}
}The final branch handles unusual or empty cases, such as ConnectionState.none without data. Do not assume that every snapshot is either loading or successful.
Data and Errors Can Be Retained
When a builder changes from one asynchronous source to another, Flutter can preserve the previous data while the new source is waiting. This lets a screen keep showing old content during a refresh. Therefore, connectionState == waiting does not always mean that the screen must become blank.
For a refresh, you might show the previous data with a small progress indicator. For an initial load, you might show a full-page spinner. The snapshot tells you what is available, but your UI decides how to combine that information.
Future and Stream Snapshot Sequences
The exact number of builder calls is not a stable API contract. Flutter may deliver intermediate snapshots, and a completed future can still produce a short waiting snapshot when attached. Write builders that handle each state safely rather than depending on an exact sequence.
Common Mistakes
A builder can crash or display the wrong screen when it:
- Reads
snapshot.data!before checkinghasData. - Shows a spinner whenever the state is not
done, hiding useful previous data. - Ignores
hasErrorand displays an empty result. - Assumes a stream always emits at least one event.
- Treats
activeas an error instead of the normal state for a live stream.
Keep the builder a pure rendering function. Start requests, manage subscriptions, and change the source outside build, usually in initState or an explicit refresh method.
Exercise
A StreamBuilder has connectionState active, hasData false, and hasError true. Which condition should the UI handle first, and why?
Show answer
Handle hasError first. The active state only says that the stream connection is still active; it does not mean the latest operation succeeded.