Flutter FutureBuilder & Async UI
Loading data from a network, a database or a file takes time. Dart represents a value that will arrive later as a Future. But a widget's build method must return immediately — it cannot await. FutureBuilder bridges this gap: it listens to a future and rebuilds itself as the future moves from waiting to done (or error).
The idea in plain Dart
First, the async part on its own. This example runs for real — the "network" is simulated with Future.delayed.
Future<List<String>> fetchCities() async {
await Future.delayed(const Duration(milliseconds: 100));
return ['Hanoi', 'Lisbon', 'Nairobi'];
}
Future<void> main() async {
print('Loading...');
final cities = await fetchCities();
print('Got ${cities.length} cities: ${cities.join(', ')}');
}Loading...
Got 3 cities: Hanoi, Lisbon, Nairobi
A UI needs to show something useful while it waits — a spinner — and then the data. That is exactly what FutureBuilder does.
FutureBuilder
FutureBuilder takes a future and a builder. The builder receives an AsyncSnapshot describing the current state.
class CityList extends StatefulWidget {
const CityList({super.key});
@override
State<CityList> createState() => _CityListState();
}
class _CityListState extends State<CityList> {
// Create the future ONCE, not inside build().
late final Future<List<String>> _cities = fetchCities();
@override
Widget build(BuildContext context) {
return FutureBuilder<List<String>>(
future: _cities,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final cities = snapshot.data!;
return ListView(
children: [for (final c in cities) ListTile(title: Text(c))],
);
},
);
}
}Note: Never write
future: fetchCities()directly insidebuild. Every rebuild would start a brand-new request and the spinner would flash forever. Create the future ininitStateor alate finalfield.
AsyncSnapshot cheat sheet
| Member | Meaning |
|---|---|
connectionState |
none, waiting, active (streams), or done |
hasData / data |
The completed value (nullable) |
hasError / error |
The error thrown by the future |
requireData |
data, or throws if there is none |
Handling errors
If the future throws, the snapshot reports hasError. Again, here is the Dart behaviour you can run:
Future<String> loadProfile(int id) async {
await Future.delayed(const Duration(milliseconds: 50));
if (id <= 0) throw StateError('No user with id $id');
return 'User #$id';
}
Future<void> main() async {
for (final id in [7, 0]) {
try {
print(await loadProfile(id));
} catch (e) {
print('Failed: $e');
}
}
}User #7
Failed: Bad state: No user with id 0
In a FutureBuilder you show an error message and often a Retry button that assigns a new future inside setState.
StreamBuilder
For data that arrives repeatedly — chat messages, a timer, location updates — use StreamBuilder. It works like FutureBuilder but rebuilds on every new event.
StreamBuilder<int>(
stream: Stream.periodic(const Duration(seconds: 1), (i) => i + 1).take(10),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Starting...');
return Text('Seconds: ${snapshot.data}',
style: Theme.of(context).textTheme.headlineMedium);
},
)Tip: For refreshable lists, wrap the content in a
RefreshIndicatorwhoseonRefreshreturns a future — the user gets pull-to-refresh for free.
Test yourself
Why should you not call fetchData() directly in the future: argument inside build?
- It is a syntax error
- Every rebuild would start a new request
- FutureBuilder only accepts streams
- It makes the app use dark mode
Which ConnectionState means the future has completed?
- waiting
- active
- done
- none
Which widget rebuilds on every new event from a stream?
- FutureBuilder
- StreamBuilder
- ListView.builder
- AnimatedBuilder