Sub topic 5
Handling Loading, Error, and Data States
This chapter assumes you know Dart async, await, and Future, plus Flutter StatefulWidget, build, setState, initState, and dispose.
An asynchronous operation does not produce a result immediately. While it runs, the UI needs a loading state. It also needs an error state when the operation fails and a data state when it succeeds. FutureBuilder and StreamBuilder expose these states through an AsyncSnapshot.
Read the snapshot
An AsyncSnapshot<T> is a record of the latest asynchronous state. The type parameter T is the type of value that the operation produces, such as String or List<Product>.
| Property | Meaning |
|---|---|
| `connectionState` | Whether the operation is waiting, active, or done |
| `data` | The latest successful value |
| `error` | The failure object, if one occurred |
| `hasData` | Whether `data` contains a non-null value |
| `hasError` | Whether an error was reported |
For a FutureBuilder, the usual states are waiting and done. A stream can also be active because it may deliver several values over time. none means that the builder is not currently connected to an asynchronous source.
A useful rendering order is:
- Check for an error.
- Check for usable data.
- Show loading or an empty state.
You can instead check connectionState first when loading must always hide older content. Choose the order deliberately.
Render all important states
The following complete example uses a button to retry a request. The request fails on the first attempt and succeeds on the next attempt, so each state can be observed.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: UserScreen()));
}
class UserScreen extends StatefulWidget {
const UserScreen({super.key});
@override
State<UserScreen> createState() => _UserScreenState();
}
class _UserScreenState extends State<UserScreen> {
late Future<String> _userFuture;
int _attempt = 0;
@override
void initState() {
super.initState();
_userFuture = _loadUser();
}
Future<String> _loadUser() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (_attempt == 0) {
throw Exception('The server is unavailable');
}
return 'Ada Lovelace';
}
void _retry() {
setState(() {
_attempt++;
_userFuture = _loadUser();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Center(
child: FutureBuilder<String>(
future: _userFuture,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Could not load profile: ${snapshot.error}'),
const SizedBox(height: 12),
ElevatedButton(
onPressed: _retry,
child: const Text('Retry'),
),
],
);
}
if (snapshot.hasData) {
return Text(
'Welcome, ${snapshot.data}!',
style: Theme.of(context).textTheme.headlineSmall,
);
}
if (snapshot.connectionState == ConnectionState.done) {
return const Text('No profile data was returned.');
}
return const CircularProgressIndicator();
},
),
),
);
}
}The first build usually receives a snapshot whose connectionState is waiting. The Future then completes. If it throws, hasError becomes true. If it returns a non-null string, hasData becomes true and data contains that string.
data and error are independent fields. Do not display snapshot.data without checking that it is available. Also remember that hasData is false when the result is null. If null is a valid result, use connectionState == ConnectionState.done and handle null explicitly.
Streams use the same model
StreamBuilder follows the same snapshot pattern, but a stream can remain connected and active while it emits values. For example, a live score might render the latest snapshot.data on every event. Handle hasError before rendering the value, and consider initialData when the screen should show something before the first event.
When a new request replaces an old one, a builder can briefly retain previous data while the new operation is waiting. If that behavior is confusing, render strictly from connectionState and keep the previous value in a separate field.
Exercise
Why should a builder check snapshot.hasError before using snapshot.data?
Show answer
A failed operation may have no usable data, and reading or displaying data first can hide the real failure or produce misleading UI.