Sub topic 10
Loading, data and error states with FutureBuilder
This chapter shows how to turn a Future from your networking code into a screen that displays a loading indicator, the data, or an error. It assumes you know Dart classes, null safety and named parameters, async/await, the StatefulWidget lifecycle, and how to add a package to pubspec.yaml. It also assumes you have the fetchPost function and Post model from the earlier chapters on GET requests and JSON models.
What FutureBuilder does
FutureBuilder<T> is a widget that listens to a Future<T> and calls your builder function each time the future's state changes. The builder receives an AsyncSnapshot<T>, which is a read-only view of the latest state of the future.
A request has three outcomes the user must be able to see:
- Loading: the request has been sent and nothing has come back.
- Data: the response arrived and was parsed.
- Error: a status check, timeout, connection failure or parsing step threw an exception.
The snapshot exposes these through a few properties:
| Property | Meaning |
|---|---|
| `connectionState` | `none`, `waiting`, `active` or `done`. For a `Future`, you see `waiting` and then `done`. |
| `hasData` | `true` when the future completed with a non-null value. |
| `hasError` | `true` when the future completed with an error. |
| `data` | The value, or `null` if there is none. |
| `error` | The thrown object, or `null`. |
| `stackTrace` | The stack trace that came with the error. |
The mistake that repeats requests
The most common bug with FutureBuilder is creating the future inside build:
// Wrong: a new request starts on every rebuild.
FutureBuilder<Post>(
future: fetchPost(client, 1),
builder: (context, snapshot) => const SizedBox(),
)Flutter can call build many times: on a setState, a keyboard appearing, a screen rotation, or a parent rebuilding. Each call would start another HTTP request, and the widget would flicker back to the loading state each time. The FutureBuilder sees a different Future object and restarts its subscription.
The fix is to create the future once and keep it in a field of a State object. This is the pattern used in the example below.
A complete screen
The following example creates the future in initState, then handles the error, loading and data cases in that order. It uses the fetchPost function and the Post class from the earlier chapter.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class PostScreen extends StatefulWidget {
const PostScreen({super.key, required this.client});
final http.Client client;
@override
State<PostScreen> createState() => _PostScreenState();
}
class _PostScreenState extends State<PostScreen> {
late final Future<Post> _post;
@override
void initState() {
super.initState();
_post = fetchPost(widget.client, 1);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Post>(
future: _post,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return Center(child: Text(snapshot.data!.title));
},
);
}
}Three details matter here:
- The client is injected. The screen receives an
http.Clientthrough its constructor. A test can pass aMockClient, which a later chapter covers. - The error check comes first. If the future failed,
hasDataisfalsetoo, so checkinghasDatafirst would show a spinner forever. late finalis safe ininitState. The field is assigned exactly once, before the firstbuild.
Why the order of checks matters
Think of the builder as a series of guards, from most specific to least:
- If
hasError, show the error. - If there is no data, show the loading indicator.
- Otherwise, show the data.
The second guard treats "no data and no error" as loading. That is accurate for a Future that has not finished. It is also accurate for a future that completed with null, but Future<Post> never completes with null, so the case does not arise here. If your future type is nullable, such as Future<Post?>, check connectionState instead:
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final post = snapshot.data;
if (post == null) {
return const Center(child: Text('Nothing found'));
}
return Center(child: Text(post.title));
}Showing errors users can act on
'Error: ${snapshot.error}' is fine for a first version, but it prints text like ApiException(404): Request failed. A user needs something they can understand and act on. Because the networking layer throws ApiException, the UI can translate the exception into a message.
String describeError(Object error) {
if (error is ApiException) {
final code = error.statusCode;
if (code == null) return error.message;
if (code == 404) return 'That item no longer exists.';
if (code >= 500) return 'The server had a problem. Try again later.';
return 'The request was rejected ($code).';
}
return 'Something went wrong.';
}This function assumes the ApiException class from the error handling chapter. Keeping the mapping in one function means every screen shows the same wording, and a log line can still record the raw exception.
Adding a retry button
An error state with no way out is frustrating. To retry, you need a new Future, which means you must replace the field and call setState. A late final field cannot be reassigned, so change it to a normal late field.
class _RetryPostScreenState extends State<RetryPostScreen> {
late Future<Post> _post;
@override
void initState() {
super.initState();
_post = fetchPost(widget.client, 1);
}
void _retry() {
setState(() {
_post = fetchPost(widget.client, 1);
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Post>(
future: _post,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(describeError(snapshot.error!)),
const SizedBox(height: 12),
FilledButton(onPressed: _retry, child: const Text('Retry')),
],
),
);
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return Center(child: Text(snapshot.data!.title));
},
);
}
}
class RetryPostScreen extends StatefulWidget {
const RetryPostScreen({super.key, required this.client});
final http.Client client;
@override
State<RetryPostScreen> createState() => _RetryPostScreenState();
}When setState assigns a new future, the FutureBuilder sees a different object. It resets to the waiting state and then shows the spinner again, which is the behavior you want after a retry.
Edge cases
Old data while refreshing
When the future changes, FutureBuilder resets the snapshot to waiting. In Flutter, the new snapshot does not keep the previous data. If you want to keep showing the old content during a refresh, store the last result in your own field, or use a state management approach. FutureBuilder alone is best for load-once screens.
Updating the screen after the widget is gone
If the user leaves the screen before the response arrives, the FutureBuilder stops listening and ignores the result. This is safe. The request itself still runs to completion. Only code that you wrote inside the future's chain, such as a setState call in a then, needs a mounted check.
Depending on a parameter
If the screen shows a post by id, the id may change when the parent rebuilds with a new value. Override didUpdateWidget to start a new request:
@override
void didUpdateWidget(covariant PostByIdScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.postId != widget.postId) {
_post = fetchPost(widget.client, widget.postId);
}
}Assigning inside didUpdateWidget does not need setState, because Flutter rebuilds the widget right after the method returns.
Hot reload
Hot reload keeps the State object, so initState does not run again and the old future stays in place. If you edit the request code and nothing changes, use a hot restart.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The request repeats and the spinner flickers | The future is created inside `build` | Store it in a `State` field |
| The spinner never stops after a failure | The builder checks `hasData` before `hasError` | Check `hasError` first |
| `Null check operator used on a null value` | `snapshot.data!` used while loading | Guard with `hasData` or `connectionState` |
| Retry button does nothing | The future was reassigned without `setState` | Wrap the assignment in `setState` |
| The spinner shows forever with no error | The future never completes, for example no timeout is set | Add a timeout in the networking layer |
Exercises
Exercise
Why does FutureBuilder(future: fetchPost(client, 1), ...) inside build cause repeated network requests, and where should the future be created instead?
Show answer
build can run many times, and each run calls fetchPost again, creating a new Future. The FutureBuilder sees a different future each time and restarts. Create the future once, in initState, and store it in a State field so rebuilds reuse it.
Exercise
A FutureBuilder shows a spinner forever when the server is unreachable. The builder checks if (!snapshot.hasData) return spinner; before anything else. What two changes fix this?
Show answer
First, check snapshot.hasError before the hasData check, so a failed future shows an error. Second, add a timeout in the networking code, for example .timeout(const Duration(seconds: 10)), so a stalled request ends with an error instead of waiting indefinitely.
Exercise
Why must the retry handler call setState when it assigns a new future to _post?
Show answer
setState marks the widget as needing a rebuild. Without it, the field changes but build does not run, so the FutureBuilder never receives the new future and the screen does not change.