Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 73 ยท Networking and data

FutureBuilder, StreamBuilder and Async UI

Show loading, error and data states in Flutter with FutureBuilder and StreamBuilder, read AsyncSnapshot correctly, avoid refetching on rebuild and add pull to refresh.

A network call takes time. For a moment your screen has no data, then it has data, or it has an error. A good app shows all three honestly: a spinner while waiting, a message when something fails, the content when it works. Flutter's FutureBuilder and StreamBuilder widgets turn a Future or a Stream into exactly that kind of UI.

They are small widgets with one tricky rule: where you create the future matters. This lesson explains AsyncSnapshot, the three states, the classic refetch-on-every-rebuild bug, and pull to refresh. It builds on HTTP Requests and JSON and Futures, async/await and Streams.

Real vs stand-in. The Dart and widget code is real Flutter, read-only here. The live examples are JavaScript stand-ins: a tiny FutureBuilder that builds from a snapshot, and a rebuild counter that reproduces the refetch bug.

One snapshot, three looks

Waiting Show a spinner.
Error Show a message and Retry.
Data Show the content.

Never leave a state without a widget.

1 / 2

FutureBuilder

FutureBuilder<T> takes a future and a builder. The builder runs first with a "waiting" snapshot, and again when the future completes.

DART
class ProductList extends StatefulWidget {
  const ProductList({super.key});

  @override
  State<ProductList> createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> {
  late final Future<List<Product>> _future = fetchProducts();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Product>>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Center(child: Text('Failed: ${snapshot.error}'));
        }
        final products = snapshot.requireData;
        return ListView(
          children: [for (final p in products) ListTile(title: Text(p.name))],
        );
      },
    );
  }
}

Reading an AsyncSnapshot

The snapshot is a small immutable value:

Property Meaning
connectionState none (no future), waiting, active (stream still open), done
hasData / data A non-null value arrived. data is null before that
hasError / error The future or stream failed
requireData The data, or throws if there is none (use after you handled other states)

A safe order for checks is: error first, then data, then waiting. Checking hasError first means a failed request never falls through to a spinner forever. If your T can legitimately be null, use hasData instead of data != null.

The refetch bug

This is the most common FutureBuilder mistake:

DART
// BAD: a new request starts on every rebuild
FutureBuilder<List<Product>>(
  future: fetchProducts(),
  builder: (context, snapshot) { /* ... */ },
)

Calling fetchProducts() inside build creates a new Future each time build runs. Anything that rebuilds the widget (a keyboard opening, a parent's setState, a theme change, rotating the phone) restarts the request and flashes the spinner. FutureBuilder sees a different future object and starts waiting again.

The fix is to create the future once, outside build: in a field initializer, in initState, or in a state-management layer (see Lifting State Up and ValueNotifier and State Management with Provider). The earlier example does this with late final Future<List<Product>> _future = fetchProducts();.

JS Refetch on every rebuild vs fetch once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three rebuilds cause three network requests in the bad version and one in the good one. In a real app each extra request is wasted battery, data and a visible flicker.

A stand-in FutureBuilder

To see the three states in order, here is a minimal builder that calls your function with a snapshot-like object.

JS Waiting, error and data snapshots

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both flows start with the spinner. The error check sits first in ui, so a failure shows its message instead of a spinner that never ends.

StreamBuilder

StreamBuilder<T> works the same way, but its builder runs every time the stream emits a new event. Use it for live data: a Firestore query, a sensor, a countdown, a chat feed (see WebSockets and Realtime Data).

DART
StreamBuilder<int>(
  stream: _countdown,            // create once, like a Future
  initialData: 10,
  builder: (context, snapshot) {
    if (snapshot.hasError) return Text('Error: ${snapshot.error}');
    switch (snapshot.connectionState) {
      case ConnectionState.waiting:
        return const CircularProgressIndicator();
      case ConnectionState.active:
        return Text('${snapshot.data} seconds left');
      case ConnectionState.done:
        return const Text('Liftoff!');
      case ConnectionState.none:
        return const Text('Not started');
    }
  },
)

The builder shows the latest event only. If you need the history (a growing list of messages), accumulate it yourself, for example by mapping the stream to a full list. A StreamBuilder listens to a stream when it mounts and cancels when it is removed, so you do not manage the subscription. Streams that can be listened to twice need asBroadcastStream() or a StreamController.broadcast().

Pull to refresh

Wrap a scrollable in RefreshIndicator and give it an async onRefresh. The spinner stays visible until the returned future completes.

DART
class _ProductListState extends State<ProductList> {
  late Future<List<Product>> _future = fetchProducts();

  Future<void> _refresh() async {
    final next = fetchProducts();
    setState(() {
      _future = next;               // a new future on purpose
    });
    await next;                     // keep the spinner until done
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Product>>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Center(
            child: FilledButton(onPressed: _refresh, child: const Text('Retry')),
          );
        }
        if (!snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }
        return RefreshIndicator(
          onRefresh: _refresh,
          child: ListView(
            children: [for (final p in snapshot.data!) ListTile(title: Text(p.name))],
          ),
        );
      },
    );
  }
}

Assigning a new future inside setState is the intentional way to refetch. Because ListView must be scrollable for the gesture to work, a short list needs physics: const AlwaysScrollableScrollPhysics(). Also notice _future is no longer final here, and the first if offers a Retry button, which is just the same refresh.

During a refresh, FutureBuilder briefly shows the waiting state again, so hasData would be false. To keep old content on screen while reloading, keep the last good list in a State field and show it under a thin progress bar, or move to a state-management package whose async types keep the previous value (see Riverpod).

When not to use these widgets

FutureBuilder is perfect for a one-off load tied to one screen. It becomes awkward when several widgets need the same data, when you want caching, or when you need to refetch from several places. At that point put the loading state in a notifier, provider or bloc and let the widget read it. The widget stays simple, and the tests get easier (Choosing State Management and App Architecture).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is future: fetchProducts() inside build a bug?

    build can run many times. FutureBuilder restarts whenever it receives a different future object.
  2. 2. In what order should a builder check an AsyncSnapshot?

    Checking the error first prevents a failed request from showing a spinner forever.
  3. 3. What is the difference between FutureBuilder and StreamBuilder?

    A Future completes once; a Stream can emit many events, and StreamBuilder rebuilds on each.
  4. 4. How do you intentionally refetch data with a FutureBuilder?

    A new future object makes FutureBuilder start waiting again. Create it in an event handler, not in build.
  5. 5. What does RefreshIndicator's onRefresh need to return?

    The indicator stays visible until the returned Future completes.

Summary

  • FutureBuilder and StreamBuilder turn async work into UI using an AsyncSnapshot.
  • Handle error, data and waiting; check the error first.
  • Create the Future or Stream once (field, initState or a notifier), never inside build.
  • Refetch on purpose by assigning a new future inside setState; RefreshIndicator needs an async onRefresh.
  • For shared or cached data, move the async state out of the widget.

Next: WebSockets and Realtime Data