Sub topic 7
Refreshing data and retrying after an error
This chapter assumes you can write async functions in Dart and build a StatefulWidget with initState and setState. It also assumes you have read the earlier chapters on AsyncSnapshot, FutureBuilder, and keeping a Future stable across rebuilds. Here you will add two features to a Future-based screen: a retry button after a failure, and a refresh that re-fetches data that loaded successfully.
Why a finished Future cannot be restarted
A Future runs once. When it completes with a value or an error, it keeps that result for good. If you pass the same Future to FutureBuilder again, you get the same result. Nothing is re-fetched.
So "retry" does not mean "ask the Future again". It means creating a new Future by calling your async function a second time, then telling Flutter to use it. Two parts make this work:
- State owns the Future. You store it in a field, as the previous chapter showed.
setStateswaps it. Replacing the field insidesetStateschedules a rebuild. During that rebuild,FutureBuildersees a different Future than before and restarts.
What FutureBuilder does when the Future changes
When the future property of a FutureBuilder changes between builds, the widget does the following:
- It stops listening to the old Future. If the old Future completes later, its result is ignored.
- It subscribes to the new Future.
- It moves the snapshot's
connectionStateback towaiting.
The last step has a detail that matters for your UI. The snapshot keeps the previous data or error while the new Future is pending. Only the connectionState changes. The snapshot is rebuilt from the previous one, not from scratch. A refresh therefore produces a snapshot that can have connectionState == waiting and hasData == true at once.
That is useful, because you can keep showing the old content during a refresh. It can also hurt you. If your builder checks snapshot.hasError first, a retry still shows the old error while the new request runs, because the error is still on the snapshot.
When the new Future finishes, the snapshot is replaced. A success clears the old error. A failure clears the old data, because an error snapshot carries no data. If you want to keep showing the last good data after a failed refresh, store it yourself in a State field.
Retrying after an error
The following widget always fails, so you can see the retry cycle. Replace the exception with a real request when you adapt it.
import 'package:flutter/material.dart';
class RetryableName extends StatefulWidget {
const RetryableName({super.key});
@override
State<RetryableName> createState() => _RetryableNameState();
}
class _RetryableNameState extends State<RetryableName> {
late Future<String> _name = _fetchName();
Future<String> _fetchName() async {
await Future<void>.delayed(const Duration(milliseconds: 500));
throw Exception('Network unavailable');
}
void _retry() {
setState(() {
_name = _fetchName();
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Failed: ${snapshot.error}'),
ElevatedButton(onPressed: _retry, child: const Text('Retry')),
],
);
}
return Text('Hello, ${snapshot.data}');
},
);
}
}Three details make this code correct:
- The field is
late Future<String> _name, notlate final. Afinalfield can be assigned only once, so_retrycould not replace it. - The builder checks
connectionState != donefirst. After you tap Retry, the snapshot still holds the old error but is inwaiting. This check shows the spinner instead of the stale error. _retryassigns insidesetState. The assignment is synchronous. The new Future starts running as soon as_fetchName()is called, and the rebuild hands it toFutureBuilder.
Choosing what to show per state
The order of your checks decides what the user sees during a retry. Use this table as a guide.
| Snapshot condition | Meaning | Typical UI |
|---|---|---|
| `connectionState == waiting`, no data | First load, or retry after an error | Spinner |
| `connectionState == waiting`, has data | Refresh of content already on screen | Old content, optionally with a thin progress bar |
| `connectionState == done`, `hasError` | The last request failed | Message and Retry button |
| `connectionState == done`, `hasData` | The last request succeeded | The content |
Refreshing data that loaded successfully
A refresh is the same mechanism as a retry. Only the trigger differs. A common trigger is pull-to-refresh with RefreshIndicator. Its onRefresh callback must return a Future, and the indicator keeps spinning until that Future completes. You can return the same Future you hand to FutureBuilder.
import 'package:flutter/material.dart';
class ItemList extends StatefulWidget {
const ItemList({super.key});
@override
State<ItemList> createState() => _ItemListState();
}
class _ItemListState extends State<ItemList> {
int _loads = 0;
late Future<List<String>> _items = _loadItems();
Future<List<String>> _loadItems() async {
await Future<void>.delayed(const Duration(milliseconds: 800));
_loads++;
if (_loads == 2) {
throw Exception('Server error on the second load');
}
return List.generate(5, (i) => 'Item $i (load $_loads)');
}
Future<void> _refresh() async {
final next = _loadItems();
setState(() {
_items = next;
});
try {
await next;
} catch (_) {
// The error is shown through the snapshot, so just let the
// RefreshIndicator finish.
}
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: _refresh,
child: FutureBuilder<List<String>>(
future: _items,
builder: (context, snapshot) {
final done = snapshot.connectionState == ConnectionState.done;
if (done && snapshot.hasError) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
ListTile(title: Text('Failed: ${snapshot.error}')),
TextButton(
onPressed: _refresh,
child: const Text('Retry'),
),
],
);
}
final items = snapshot.data;
if (items != null) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [for (final item in items) ListTile(title: Text(item))],
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}Walk through what happens when the user pulls down on this list:
_refreshcalls_loadItems()and stores the result innext. The request starts now.setStateassignsnextto_items. The next build givesFutureBuilderthe new Future.- The snapshot goes to
waitingand keeps the old list. Thedone && hasErrorcheck fails anditems != nullpasses, so the old list stays visible. _refreshawaitsnext. TheRefreshIndicatorshows its spinner until_refreshreturns.- The second load throws. The snapshot becomes
donewith an error and no data, so the failure view appears. Thecatchkeeps the exception from escaping_refresh. - The Retry button calls
_refreshagain. That load succeeds and the new list replaces the error view.
Some details in this example are easy to miss:
- Physics.
RefreshIndicatorreacts only to scroll gestures. If the list is shorter than the screen, a defaultListViewcannot overscroll and pull-to-refresh never fires.AlwaysScrollableScrollPhysicsfixes that. The error view uses aListViewfor the same reason: it lets the user pull to refresh even on the failure screen. - The Future is created before
setState. That keeps thesetStatecallback to a single assignment and gives_refresha handle to await. - The catch block. Without it, an error in
await nextwould propagate out ofonRefreshas an unhandled exception, even though the UI already displays it.
Alternative: restarting with a key
You can also restart FutureBuilder by changing its key. The framework then discards the old FutureBuilder state and creates a new one, so the snapshot starts from none and carries no old data or error.
FutureBuilder<String>(
key: ValueKey(_attempt),
future: _name,
builder: (context, snapshot) {
// ...
},
)You still need a new Future in _name. The key only controls whether the old snapshot survives. Compare the two approaches:
| Technique | Old data during reload | Cost | Use when |
|---|---|---|---|
| New Future in `setState` | Kept on the snapshot while waiting | Minimal | You want to show stale content during a refresh |
| New Future plus a changed `key` | Dropped immediately | Rebuilds the builder's subtree state | You want a clean spinner and no stale data or errors |
For most screens the first technique is enough. You can get the clean-spinner behavior without a key by checking connectionState first, as the retry example does.
Failure modes to watch for
- Double taps. Two quick taps on Retry start two requests.
FutureBuilderignores the first one's result, since it listens only to the latest Future, but the first request still runs and may have side effects on the server. For non-idempotent calls, track an_isLoadingflag and setonPressedtonullwhile it is true. - Retry storms. Calling
_retryautomatically from the builder is a bug. It would create a new Future duringbuild, which fails on every rebuild. If you want automatic retry, put it in the data layer with a capped attempt count and a delay that grows between attempts (exponential backoff). Keep the UI trigger manual. - Forgetting
setState. Assigning_name = _fetchName();withoutsetStatestarts a request, but nothing rebuilds. The screen keeps showing the old result, and the new Future's outcome is never displayed. - Reading
erroras a string.snapshot.erroris anObject?. It is fine to interpolate in a demo. In a real app, map exceptions to user-facing messages and log thestackTrace. - Streams are different. A
StreamBuilderkeeps listening after an error event, and a stream that has ended cannot restart. To resume, create a newStreamand assign it withsetState, the same technique this chapter uses for Futures. The next chapters cover streams in detail.
Summary of the technique
- Keep the Future in a non-
finalStatefield. - Write one method that creates the Future and assigns it inside
setState. - In the builder, check
connectionStatebeforehasErrorso a retry does not show the old error. - Reuse that method for the Retry button and for
RefreshIndicator.
Exercise
In the retry example, _retry assigns a new Future inside setState. A teammate removes setState and writes only _name = _fetchName();. Tapping Retry then does nothing visible. Why, and what extra problem can it cause?
Show answer
Nothing triggers a rebuild, so FutureBuilder never receives the new Future and the screen keeps showing the error. The request still runs in the background, so you pay for a network call whose result is never displayed. Wrapping the assignment in setState schedules the rebuild that passes the new Future to FutureBuilder.
Exercise
Your builder checks if (snapshot.hasError) before it checks connectionState. After a failure, the user taps Retry and the request takes three seconds. What does the screen show during those three seconds, and how do you fix the builder?
Show answer
It keeps showing the old error and the Retry button. When the Future changes, the snapshot moves to waiting but keeps the previous error, so hasError stays true. Fix it by checking snapshot.connectionState != ConnectionState.done first and returning the spinner, or by changing the FutureBuilder key so the old snapshot is discarded.
Exercise
A pull-to-refresh list works when it has 30 items but does nothing when the server returns only 3. What is the likely cause and the fix?
Show answer
A ListView whose content fits on screen is not scrollable by default, so it never overscrolls and the RefreshIndicator is never triggered. Set physics: const AlwaysScrollableScrollPhysics() on the ListView. Do the same in the error view so the user can pull to refresh there too.