Sub topic 5
Handling Loading, Error, and Data States
This chapter assumes you can write async and await code in Dart, and that you know StatefulWidget, setState, and the initState and dispose lifecycle. It also assumes you have seen a basic FutureBuilder and know that its builder runs again whenever its Future changes state.
A FutureBuilder or StreamBuilder calls your builder with an AsyncSnapshot. The builder must turn that snapshot into a widget in every state it can be in. Most bugs in async screens come from the builder handling one state well and the others badly. A screen may flash an error after a retry, show a blank frame, or treat an empty result as a failure. This chapter covers the states a snapshot can be in, the order in which to test them, and the edge cases that catch people out.
The Four Questions a Snapshot Answers
An AsyncSnapshot<T> is an immutable description of the latest interaction with the async source. You will use these members most often:
connectionState: aConnectionStatevalue:none,waiting,active, ordone.hasData: true when the snapshot holds a non-null value.data: the value, ornull.hasError: true when the snapshot holds an error.errorandstackTrace: the error and its stack trace.requireData: returns the value, or throws if there is none. Use it only after you have checkedhasData.
For a Future, connectionState moves from waiting to done. For a Stream, it moves from waiting to active on the first event, then to done if the stream closes. The none state means no future or stream was given, or the builder has unsubscribed.
| Situation | connectionState | hasData | hasError |
|---|---|---|---|
| Future started, not finished | waiting | false | false |
| Future completed with a value | done | true | false |
| Future completed with an error | done | false | true |
| Future completed with `null` | done | false | false |
| Stream subscribed, no event yet | waiting | false | false |
| Stream emitted a value | active | true | false |
| Stream closed | done | depends on the last event | depends on the last event |
The fourth row is a common source of bugs. hasData means "the data is not null", not "the future finished successfully". A Future<void> never has data. A Future<String?> that returns null also reports hasData == false. If you treat "no data" as "still loading", the spinner spins forever.
Choosing a Test Order
You can test the states in several orders, and the order changes behavior. Pick one deliberately.
For a FutureBuilder, the safest order is:
- If
connectionStateis notdone, show the loading view. - If
hasError, show the error view. - If
hasData, show the data view. - Otherwise show an "empty" view.
Step 1 comes first for a reason that is easy to miss. When the future changes, FutureBuilder unsubscribes from the old one and subscribes to the new one. The new snapshot is in the waiting state, but it keeps the previous data or error. If you test hasError first, an old error stays on screen while the retry is running. If you test hasData first, old data stays on screen during a refresh. Showing old data during a refresh is sometimes what you want, and we come back to it below. Showing an old error while a retry runs is almost never what you want.
Here is a complete widget that follows this order. It uses Future<String?> on purpose so the null case is visible.
import 'package:flutter/material.dart';
class NicknameView extends StatefulWidget {
const NicknameView({super.key});
@override
State<NicknameView> createState() => _NicknameViewState();
}
class _NicknameViewState extends State<NicknameView> {
late final Future<String?> _nickname;
@override
void initState() {
super.initState();
_nickname = _loadNickname();
}
Future<String?> _loadNickname() async {
await Future<void>.delayed(const Duration(seconds: 1));
return null; // This user has not set a nickname.
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String?>(
future: _nickname,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return const Center(child: Text('Could not load your nickname.'));
}
final nickname = snapshot.data;
if (nickname == null) {
return const Center(child: Text('No nickname set'));
}
return Center(child: Text(nickname));
},
);
}
}The future is created once in initState and stored in the State object. The next chapter explains why. Here, notice that "finished with null" gets its own message instead of falling into the loading branch.
Loading States
A loading view has one job: tell the user something is happening without disturbing the layout. A few practical rules:
- Give the spinner the same space the content will use, or center it in the available area. A spinner that is 40 pixels tall replaced by a 600-pixel list makes the page jump.
- Use
CircularProgressIndicatorfor unknown duration. Use a skeleton or placeholder layout when you know the shape of the content. - Don't show a spinner for a
Futurethat has already completed. BecauseFutureBuilderstarts inwaitingeven for an already-completed future, you may see one frame of spinner. PassinitialDatato theFutureBuilderif you have a cached value and want that frame to show it.
If the state is none, the builder has no future or stream. This happens when you pass a nullable future and it is null. Treat none as "nothing to show yet", for example a search screen before the user has typed a query.
Error States
A Future that throws delivers the error to the snapshot. It does not crash the app and it does not propagate to the caller. The error appears only if your builder reads it. If you never check hasError, a failed request looks identical to an empty one, and nothing reports the problem.
Follow these rules for error views:
- Show a message for the user, not
snapshot.error.toString(). A raw exception such asSocketException: Failed host lookupmeans nothing to most users and may expose internal details. - Log the real error and
snapshot.stackTracesomewhere you can read them. The builder runs during layout and can run many times, so log from the code that makes the request, not from the builder. - Offer a way out. A retry button is the usual one, and the chapter after this one builds it.
- Don't assume the error type.
snapshot.erroris anObject?. Check withisif you want different messages for different failures.
String messageFor(Object? error) {
if (error is TimeoutException) {
return 'The request took too long. Please try again.';
}
return 'Something went wrong. Please try again.';
}TimeoutException comes from dart:async, so add import 'dart:async'; where you use it.
For streams, errors are not final. A stream can emit an error event and then keep emitting values. Each event replaces the snapshot, so after an error event the snapshot has hasError == true and no data. When the next value arrives, hasError becomes false again. A stream-driven screen therefore needs an error view that can disappear by itself.
A Reusable Helper
Once you have written the same four-branch builder a few times, extract it. The helper below works for both futures and streams, because it tests waiting and none rather than done.
import 'package:flutter/material.dart';
Widget buildAsync<T extends Object>(
AsyncSnapshot<T> snapshot, {
required Widget Function(T value) onData,
Widget Function(Object error)? onError,
Widget? empty,
}) {
final state = snapshot.connectionState;
if (state == ConnectionState.waiting || state == ConnectionState.none) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
final error = snapshot.error!;
return onError != null
? onError(error)
: const Center(child: Text('Something went wrong.'));
}
if (snapshot.hasData) {
return onData(snapshot.requireData);
}
return empty ?? const Center(child: Text('Nothing to show'));
}Because T extends Object, a null value can never be valid data, so the final branch is reachable only when the source finished without producing a value.
Use it with a list. This widget separates "the request succeeded and returned no items" from every other state:
import 'package:flutter/material.dart';
class TaskList extends StatefulWidget {
const TaskList({super.key});
@override
State<TaskList> createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
late final Future<List<String>> _tasks;
@override
void initState() {
super.initState();
_tasks = _loadTasks();
}
Future<List<String>> _loadTasks() async {
await Future<void>.delayed(const Duration(milliseconds: 800));
return <String>['Write chapter', 'Review code'];
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<String>>(
future: _tasks,
builder: (context, snapshot) => buildAsync<List<String>>(
snapshot,
onData: (tasks) {
if (tasks.isEmpty) {
return const Center(child: Text('No tasks yet'));
}
return ListView(
children: [
for (final task in tasks) ListTile(title: Text(task)),
],
);
},
),
);
}
}An empty list is a successful result. hasData is true for <String>[], so the empty-list message belongs inside onData, not in the empty branch of the helper.
Showing Stale Data on Purpose
Sometimes you want old content to stay visible while new content loads, as in pull-to-refresh. The retained data in the snapshot makes this possible. Change step 1 so it only shows a spinner when there is nothing else to show:
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('Hello, ${snapshot.data}');
}
if (snapshot.hasError &&
snapshot.connectionState == ConnectionState.done) {
return Text('Failed: ${snapshot.error}');
}
return const CircularProgressIndicator();
}This version shows the last good value during a refresh. It also never shows an error while a request is running. The cost is that the user cannot tell whether the visible data is current. If that matters, add a small indicator such as a LinearProgressIndicator when connectionState == ConnectionState.waiting && snapshot.hasData.
Common Errors
- Infinite spinner on a nullable result. The builder waits for
hasData, but the future returnednull. TestconnectionStatefirst. - Error never shown. The builder checks
hasDataand falls through to a spinner or blank widget. Always have ahasErrorbranch. - Old error visible during retry.
hasErroris tested beforeconnectionState. Test the loading state first. - Empty list treated as an error. Code checks
snapshot.data!.isEmptyin the error branch. An empty list is data. - Force-unwrapping
snapshot.data!. This throws when the snapshot has an error or no value yet. UsehasDatafirst, orrequireDataafter it. - Layout jumping. The loading view and the data view have very different sizes. Reserve space or use a placeholder.
Exercise
A FutureBuilder<int?> calls an API that returns null when a record does not exist. The builder is if (!snapshot.hasData) return CircularProgressIndicator(); return Text('${snapshot.data}');. What does the user see when the record does not exist, and how do you fix it?
Show answer
The user sees a spinner forever. The future completes with null, so hasData is false even though connectionState is done. Fix it by testing snapshot.connectionState != ConnectionState.done first for the spinner, then checking hasError, then handling snapshot.data == null with a "not found" view before showing the number.
Exercise
A screen shows an error message with a Retry button. After the user taps Retry, the old error text stays on screen until the new request finishes. The retry code assigns a new Future inside setState. What is wrong in the builder, and what is the fix?
Show answer
The builder checks snapshot.hasError before checking connectionState. When the future changes, the new snapshot is in the waiting state but keeps the previous error, so hasError is still true. Move the check connectionState != ConnectionState.done ahead of the error check so the loading view appears during the retry.
Exercise
A StreamBuilder<int> emits 1, then an error, then 2. What are hasData and hasError after each event?
Show answer
After 1: hasData is true and hasError is false. After the error: hasData is false and hasError is true, because each event replaces the snapshot. After 2: hasData is true and hasError is false again. A stream error does not end the stream, so the error view has to be able to disappear.