TExcelTAD
Home › Flutter › FutureBuilder & Async UI

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.

dart · try it yourself
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.

flutter · try it yourself
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 inside build. Every rebuild would start a brand-new request and the spinner would flash forever. Create the future in initState or a late final field.

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:

dart · try it yourself
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.

flutter · try it yourself
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 RefreshIndicator whose onRefresh returns 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?

  1. It is a syntax error
  2. Every rebuild would start a new request
  3. FutureBuilder only accepts streams
  4. It makes the app use dark mode

Which ConnectionState means the future has completed?

  1. waiting
  2. active
  3. done
  4. none

Which widget rebuilds on every new event from a stream?

  1. FutureBuilder
  2. StreamBuilder
  3. ListView.builder
  4. AnimatedBuilder