Sub topic 7
Refreshing Data and Retrying After an Error
This chapter assumes you know Dart async and await, Flutter StatefulWidget, setState, initState, and dispose. The focus is controlling a Future after the first request: starting it again, showing progress, and recovering from errors.
A refresh means creating a new Future
A Future represents one eventual result. Once it completes, it does not run again. To refresh the data, call the asynchronous operation again and give FutureBuilder the new Future.
The important part is where you create that new Future. Store the current Future in the widget's State. Change it inside an event handler such as a refresh callback or retry button.
import 'package:flutter/material.dart';
class UserGreeting extends StatefulWidget {
const UserGreeting({super.key});
@override
State<UserGreeting> createState() => _UserGreetingState();
}
class _UserGreetingState extends State<UserGreeting> {
late Future<String> _nameFuture;
@override
void initState() {
super.initState();
_nameFuture = _loadName();
}
Future<String> _loadName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
void _refresh() {
setState(() {
_nameFuture = _loadName();
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _nameFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 12),
Text('Loading...'),
],
);
}
if (snapshot.hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Could not load the name: ${snapshot.error}'),
ElevatedButton(
onPressed: _refresh,
child: const Text('Retry'),
),
],
);
}
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Hello, ${snapshot.data}'),
ElevatedButton(
onPressed: _refresh,
child: const Text('Refresh'),
),
],
);
},
);
}
}At startup, initState creates the first request. When the user taps a button, _refresh runs. setState assigns a new Future, so FutureBuilder subscribes to that request and rebuilds as its state changes.
Preserve old data during a refresh
A basic refresh shows a loading indicator while the new request runs. That is clear, but it can make the screen briefly empty. For a better experience, keep the last successful value in a separate field and show it with a smaller progress indicator.
This approach separates two ideas:
_nameFuturecontrols the current request._lastNamepreserves content already shown to the user.
You can also use snapshot.data while the new future is waiting. When a new Future replaces an old one, Flutter may retain the previous snapshot data during the transition. Do not depend on that behavior for important UI. Store data explicitly when you need predictable presentation.
Avoid overlapping requests
A user can tap a retry button repeatedly before the first new request finishes. Each tap can start another request. The results may complete in a different order, which can make the displayed data confusing.
Disable the button while loading:
final isLoading = snapshot.connectionState == ConnectionState.waiting;
ElevatedButton(
onPressed: isLoading ? null : _refresh,
child: Text(isLoading ? 'Loading...' : 'Refresh'),
)For more complex screens, track a request identifier or use a state-management solution that cancels or ignores outdated results. A Future itself does not automatically cancel the underlying network operation.
Refreshing a Stream
A Stream normally represents an ongoing source rather than one request. You usually refresh it by changing the query, recreating the stream, or sending a refresh command to the repository. Do not create a new stream inside build for the same reason you avoid creating a new Future there: each rebuild can create a new subscription.
Exercise
Exercise
Why should a retry handler assign a new Future inside setState instead of calling the asynchronous method from build?
Show answer
Assigning a new Future starts one deliberate request and makes FutureBuilder subscribe to it. Calling the method from build creates a new request whenever the widget rebuilds, which can cause repeated requests and perpetual loading.