Sub topic 2
Handling loading, error, and data states
This chapter assumes you know Dart async/await and Future, can write a StatefulWidget, and understand setState and the initState and dispose lifecycle methods.
A FutureBuilder rebuilds its child from an AsyncSnapshot. The snapshot has three parts you read most often: connectionState, hasError, and data. connectionState tells you whether the Future is still running (waiting) or has finished (done). Check connectionState first, then decide between the error view and the data view.
Rendering the three states
The example below shows a spinner while the Future runs, an error message with a retry button if it fails, and the result otherwise.
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> _name;
@override
void initState() {
super.initState();
_name = _fetchName();
}
Future<String> _fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
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}');
},
);
}
}Do not create the Future inside build
build runs again whenever the parent rebuilds or setState is called. If you call the async function directly in build, FutureBuilder receives a new Future each time. The request starts again, and the snapshot resets to waiting.
// Anti-pattern: a new request starts on every rebuild.
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _fetchName(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'Loading...');
},
);
}Store the Future in a field, create it in initState, and pass the same object to FutureBuilder on every build.
Refreshing and retrying after an error
To retry, assign a new Future to the field inside setState. FutureBuilder then subscribes to the new Future and shows the waiting state again. The _retry method in the first example does this. Do not call _fetchName() directly inside the button's onPressed without setState, because the widget would not update its future.
Exercise
In the anti-pattern above, why does the spinner appear again after each parent rebuild?
Show answer
Each rebuild calls _fetchName() again, which creates a new Future. FutureBuilder sees a different Future, resets the snapshot to waiting, and starts a new request. Store the Future in State and create it once in initState to prevent this.