Sub topic 12
When Builders Are Not Enough
FutureBuilder and StreamBuilder solve one problem well: turning one async source into widgets inside one State. This chapter covers where that stops working and what to use instead. It assumes you can read an AsyncSnapshot, you know why a Future must be created outside build, and you have closed a StreamController in dispose.
What builders do well
A builder suits you when all of these hold:
- One widget subtree needs the value.
- The async source is created when that subtree appears and can be thrown away when it disappears.
- The screen only needs the three basic views: waiting, error, data.
- You do not need to combine the result with other async sources or with user input.
Examples are a one-off detail page that loads a record, or a small widget that shows a clock tick or a sensor reading. In these cases a builder plus a Future or Stream stored in State is the simplest correct code. Adding a state management library there only adds code.
Limits you will hit
The data lives and dies with the State
The Future you store in State is created in initState and dropped when the widget leaves the tree. If the user navigates away and back, the request runs again and the screen shows a spinner again. A builder has no cache. You can keep the Future in a parent widget that outlives the child, but then the parent is doing the job of a state holder.
Sharing means lifting the source
Suppose a profile name appears in an app bar and in a settings page. With builders, each place either starts its own request or receives the same Future passed down through constructors. Passing it down works until the tree gets deep. Each consumer also gets the same snapshot behavior, which may not be what you want. For example, one consumer may want to keep showing old data while another shows a spinner.
The snapshot has no "refreshing with old data" state
ConnectionState describes the subscription to a single Future. When you assign a new Future in setState, as in a retry, the snapshot goes back to waiting and the old data is gone. Pull-to-refresh normally wants the old list to stay on screen while new data loads. You can work around this by copying the last value into a field of State, but at that point you have written your own state holder with a builder on top.
Combining sources gets awkward
Showing a screen that depends on two futures means nesting two FutureBuilders, or using Future.wait and handling a single combined failure. Streams are harder. If a screen depends on a search query stream and a results stream, builders have no operators for combining, debouncing, or switching between them. You would have to wire that in plain Dart before the builder sees it.
Writes and actions are not covered
Builders read. They say nothing about what happens when the user taps "save" while the load is still running, or when a second tap happens during a request. Guarding against duplicate submissions, tracking a pending action, and showing a failure from a write all need state that is separate from the snapshot.
Business logic ends up in widgets
The Future is created in State, so the data-fetching call, error handling, and parsing tend to end up in a widget class. That makes the logic hard to test without pumping a widget. It also makes it hard to reuse from another screen.
The following table summarizes the symptoms and what addresses them.
| Symptom | Why a builder struggles | What helps |
|---|---|---|
| Spinner appears every time the user returns to the screen | The source dies with the `State` | A state holder that outlives the widget |
| Two screens show the same data | The source is private to one `State` | Shared object provided above both screens |
| Old data disappears during refresh | A new `Future` resets the snapshot | State type with a "refreshing" case |
| Need to combine, debounce, or switch streams | No operators in the builder | Stream transformations or a state holder |
| Duplicate taps start duplicate requests | Builders only read | An explicit controller with an in-flight flag |
| Logic is hard to unit test | Fetching lives in a widget | Logic in a plain Dart class |
A hand-written alternative: a controller with explicit state
You do not need a package to move past builders. The Flutter SDK already has ChangeNotifier and ListenableBuilder. The idea is to describe the screen state as a type you control, keep it in a plain Dart object, and rebuild when it changes.
The next example defines a sealed state type with three cases, a controller that loads data, and a widget that renders each case. It needs Dart 3 and Flutter 3.10 or later.
import 'package:flutter/material.dart';
sealed class LoadState<T> {
const LoadState();
}
class Loading<T> extends LoadState<T> {
const Loading();
}
class Failure<T> extends LoadState<T> {
const Failure(this.error);
final Object error;
}
class Loaded<T> extends LoadState<T> {
const Loaded(this.value);
final T value;
}
class ProfileController extends ChangeNotifier {
ProfileController(this._fetch) {
load();
}
final Future<String> Function() _fetch;
LoadState<String> _state = const Loading();
int _generation = 0;
bool _disposed = false;
LoadState<String> get state => _state;
Future<void> load() async {
final id = ++_generation;
_state = const Loading();
notifyListeners();
try {
final value = await _fetch();
if (_disposed || id != _generation) return;
_state = Loaded(value);
} catch (error) {
if (_disposed || id != _generation) return;
_state = Failure(error);
}
notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late final ProfileController _controller;
@override
void initState() {
super.initState();
_controller = ProfileController(() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
return switch (_controller.state) {
Loading() => const CircularProgressIndicator(),
Failure(:final error) => Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Failed: $error'),
ElevatedButton(
onPressed: _controller.load,
child: const Text('Retry'),
),
],
),
Loaded(:final value) => Text('Hello, $value'),
};
},
);
}
}Several things changed compared with a plain FutureBuilder:
- Exhaustive cases. Because
LoadStateis sealed, the compiler reports an error if theswitchmisses a case. A snapshot lets you forgethasErrorand compiles anyway. - Logic outside the widget.
ProfileControllercan be unit tested with a fake_fetchfunction and no widget tree. - Stale responses are ignored. The
_generationcounter makes sure that ifloadis called twice, only the latest response is applied. A builder gets this for free by switching to the newFuture, but a hand-written controller must do it explicitly. - Safe after disposal. The
_disposedflag prevents callingnotifyListenersafter the controller was disposed, which would throw.
The controller can be extended with a case such as Refreshing(this.previous) to keep old data on screen. That is the thing the builder snapshot could not express.
Where packages fit
Once you share state, cache it, and combine sources, you are re-implementing what state management libraries provide. You do not need to learn their details here, but you should recognize what they offer.
- Provider with
ChangeNotifier. Puts the controller above the widgets that need it and rebuilds only the widgets that read it. This is the smallest step from the example above. - Riverpod. Offers
FutureProviderandStreamProvider, which expose loading, error, and data as one value and cache results by provider. Parameterized providers handle "load item by id" without hand-written maps. - Bloc or Cubit. Models events and states explicitly. It suits teams that want a strict, testable flow from user action to state.
- A repository that exposes a
Stream. The data layer owns a stream of the current value. Screens useStreamBuilderover it, and the repository handles caching and refresh. Builders and architecture work together here.
These tools differ in style, not in the underlying idea. Each one holds async state outside any single widget and tells the UI when it changes. Pick the one your team already uses before introducing a new one.
Deciding
Use the questions below, in order, to decide.
A few rules of thumb back this up:
- Start with a builder. Move away only when you can name the specific limit you hit.
- If the same data is requested in two places, stop passing futures around and share a state holder.
- If you find yourself copying
snapshot.datainto aStatefield, you need a state type with more cases than a snapshot has. - If a test needs to pump a widget just to check fetching logic, move the logic into a plain class.
Common mistakes when leaving builders
- Replacing a builder too early. A one-screen loader gains nothing from a package. The extra layers make the code harder to read.
- Nesting builders to combine sources. Two or three nested builders hide the real dependency between them. Combine in the data layer instead.
- Skipping the generation check. A hand-written controller that does not ignore stale responses can show data from an older request after a newer one.
- Notifying after dispose. Calling
notifyListenerson a disposedChangeNotifierthrows. Guard async continuations as shown above. - Creating the controller in
build. This repeats the stored-Futurebug in a new form. Create it ininitStateor above the widget in the tree.
Exercise
A screen loads a product list with a FutureBuilder. Users now want pull-to-refresh that keeps the old list visible while the new one loads, and the same list also appears on a second tab. Name two limits of the plain builder approach this runs into, and describe the state type you would use instead.
Show answer
First, assigning a new Future in setState resets the snapshot to waiting, so the old list disappears during refresh. Second, the Future is private to one State, so the second tab would start its own request or need the Future passed down. Use a state holder above both tabs, such as a ChangeNotifier, with a sealed state type that has Loading, Failure, Loaded, and Refreshing(previous) cases. The Refreshing case carries the old list so the UI can keep showing it.
Exercise
In the ProfileController example, what would go wrong if the _generation check were removed and the user tapped Retry twice quickly, with the first request finishing last?
Show answer
The older response would arrive after the newer one and overwrite the state with stale data. The generation counter ensures that only the response from the latest call to load is applied.