Sub topic 10
Loading, data and error states with FutureBuilder
This chapter assumes you know Dart classes, null safety, Future and async/await, basic Flutter widgets, and the StatefulWidget lifecycle. You will use FutureBuilder to connect an HTTP request to a widget without starting a new request on every rebuild.
The three request states
A network request normally moves through three UI states:
- Loading: the request is still running.
- Data: the request completed successfully.
- Error: the request failed.
FutureBuilder<T> listens to a Future<T> and rebuilds its child when the future changes state. The type parameter T describes the successful result, such as Post.
Create the future in `initState`
The most common mistake is creating the future inside build. Flutter can call build many times because of screen updates, parent changes, or device rotation. If the request is created there, the app may send the same request repeatedly.
Create it once in initState instead:
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 Scaffold(
appBar: AppBar(title: const Text('Post')),
body: FutureBuilder<Post>(
future: _post,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(
child: Text('Could not load the post: ${snapshot.error}'),
);
}
final post = snapshot.data;
if (post == null) {
return const Center(child: Text('No post was returned.'));
}
return Padding(
padding: const EdgeInsets.all(16),
child: Text(
post.title,
style: Theme.of(context).textTheme.headlineSmall,
),
);
},
),
);
}
}The fetchPost function represents the API client function that returns Future<Post>. The Post model represents the decoded JSON response.
connectionState tells you whether the future is waiting, active, done, or none. For a usual HTTP request, the important states are waiting and done. Check snapshot.hasError before reading snapshot.data, because a failed future does not provide valid data.
Refreshing the request
A late final future cannot be replaced. That is useful when the request should run only once. For pull-to-refresh or a retry button, store a replaceable future instead:
Future<Post>? _post;
void _loadPost() {
setState(() {
_post = fetchPost(widget.client, 1);
});
}Pass _post to FutureBuilder. A retry button can call _loadPost, which creates a new future and causes the widget to rebuild.
Exercise
Exercise
Why should an HTTP future usually be created in initState instead of build?
Show answer
Flutter may call build many times. Creating the future in initState prevents those rebuilds from sending duplicate requests.