Sub topic 12
When Builders Are Not Enough
Assume you know Dart async and await, Future, and Stream. You should also know StatefulWidget, build, setState, initState, and dispose.
FutureBuilder and StreamBuilder are useful when one widget owns one asynchronous value. They become awkward when the same data must be shared, cached, refreshed, combined, or used by several screens. A builder is a rendering tool. It does not automatically provide application-wide state management.
What builders handle well
A builder works well when:
- One screen requests one resource.
- The resource belongs to that screen.
- Loading, error, and success states are enough.
- The widget can safely recreate or replace the request at known times.
- No other screen needs the same result immediately.
For example, a profile page can own a Future<User> and pass it to FutureBuilder. The builder converts the current AsyncSnapshot<User> into widgets. This keeps the data flow easy to follow.
The design becomes less clear when several concerns appear together:
- A list and a detail page need the same cached data.
- A refresh should update multiple widgets.
- Several requests depend on one another.
- A request must be cancelled when a search query changes.
- The UI needs states such as empty, stale, refreshing, partial, and offline.
- Business rules should be tested without constructing widgets.
In those cases, move asynchronous work out of the widget tree.
Choose a state owner
A state owner is an object responsible for loading data, storing it, and exposing changes. Common choices include ChangeNotifier, ValueNotifier, a reactive state-management package, or an architecture built around streams.
The owner should usually contain:
- The current value.
- Loading and error information.
- Commands such as
load,refresh, orretry. - Rules for caching and replacing old data.
- The lifecycle of subscriptions.
The widget then observes the owner and renders its state. It does not decide how an HTTP request works.
Compare the main approaches
| Approach | Best fit | Main limitation |
|---|---|---|
| `FutureBuilder` | One request and one screen | State is tied to the widget |
| `StreamBuilder` | Repeated events or live data | Subscription lifecycle needs care |
| `ValueNotifier` | Small local state with one current value | Limited structure for complex state |
| `ChangeNotifier` | Shared mutable view state | Notifications do not describe what changed |
| Dedicated state package | Large apps and complex dependencies | Adds concepts and project conventions |
The choice depends on scope, not popularity. Do not introduce a state-management package just to replace a five-line FutureBuilder. Do introduce a state owner when widgets are duplicating requests or coordinating unrelated asynchronous operations.
Keep old data while refreshing
A common mistake is to replace useful data with a full-screen spinner every time the user refreshes. A state owner can preserve the old value while reporting that a refresh is in progress.
class ScreenState<T> {
const ScreenState({
this.data,
this.error,
this.loading = false,
});
final T? data;
final Object? error;
final bool loading;
ScreenState<T> copyWith({
T? data,
Object? error,
bool? loading,
}) {
return ScreenState<T>(
data: data ?? this.data,
error: error,
loading: loading ?? this.loading,
);
}
}This model distinguishes “no data yet” from “refreshing existing data.” A UI can show the old list, a refresh indicator, and an error message at the same time. In production code, define explicitly how a successful result clears an old error and how a failed refresh preserves old data.
Avoid lifecycle and race-condition bugs
When a query changes quickly, an older request may finish after a newer request. If its result is applied last, the screen displays stale data. A state owner can prevent this with a request token, a cancellable operation, or a stream transformation such as switchMap, depending on the library.
Subscriptions also need ownership. A StreamController created by a state owner must be closed when that owner is disposed. A stream supplied by another object should not be closed by a widget that does not own it.
Test the state owner separately from the UI. Verify initial loading, success, failure, retry, refresh with existing data, and out-of-order responses. Then use widget tests to verify only the important rendering decisions.
Exercise
A dashboard and a detail screen both request the same account data, and refresh must update both. Should each screen create its own FutureBuilder request?
Show answer
No. Use a shared state owner or repository-backed state model. It can cache the account, expose refresh and error states, and notify both screens without duplicating requests.