Sub topic 10
Modeling loading and error states
This chapter assumes you have a TodoListViewModel built on ChangeNotifier, a TodoRepository interface, and a view that rebuilds through ListenableBuilder, as in the earlier chapters. You should be comfortable with async/await, try/catch/finally, and Dart 3 sealed classes and switch expressions.
Why asynchronous work needs explicit state
A repository call takes time and can fail. During that time the view must show something, and afterward it must show either data or an error. If the view model does not model these phases, the widget has to guess them, which pushes logic back into the UI.
The view model should answer one question for the view: "What should I show right now?" That answer is the async state. It has three phases:
- Loading: a request is in flight and there is no result yet.
- Loaded: the request succeeded and the data is available.
- Failed: the request threw, and the view has an error to show.
The flags approach and its limits
The earlier view model used separate fields: isLoading, error, and todos. This works, and it is the simplest option. Its weakness is that the fields can disagree.
| Combination | Meaning | Reachable by mistake? |
|---|---|---|
| `isLoading: true`, `error: null` | Loading | No, this is valid |
| `isLoading: false`, `error: null` | Loaded | No, this is valid |
| `isLoading: false`, `error: set` | Failed | No, this is valid |
| `isLoading: true`, `error: set` | Meaningless | Yes, if you forget to clear `error` |
Each field is correct on its own, but together they allow a state that has no meaning. The usual causes are forgetting to reset _error = null before a retry and forgetting to set _isLoading = false on one code path. The finally block in the earlier load() guards against the second mistake. Nothing guards against the first except discipline.
There is also a view-side cost. Every widget that reads these fields must check them in the right order. Check error before isLoading in one widget and after it in another, and the two screens behave differently.
One value for one phase
A sealed class makes the invalid combinations impossible to write. The view model holds exactly one state object, and the compiler checks that the view handles every case.
sealed class LoadState<T> {
const LoadState();
}
class Loading<T> extends LoadState<T> {
const Loading();
}
class Loaded<T> extends LoadState<T> {
const Loaded(this.data);
final T data;
}
class Failed<T> extends LoadState<T> {
const Failed(this.error);
final Object error;
}Loaded carries data and Failed carries an error. Loading carries neither, so no field can be left over from an earlier phase.
The following diagram shows the transitions the view model allows.
The view model with a single state
This version replaces the three fields with _state. It also handles two problems that appear as soon as load() can be called more than once: results that arrive out of order, and results that arrive after disposal.
import 'package:flutter/foundation.dart';
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
LoadState<List<Todo>> _state = const Loading();
int _requestId = 0;
bool _disposed = false;
LoadState<List<Todo>> get state => _state;
Future<void> load() async {
final requestId = ++_requestId;
_state = const Loading();
notifyListeners();
try {
final todos = await _repository.fetchTodos();
if (_isStale(requestId)) return;
_state = Loaded(todos);
} catch (e) {
if (_isStale(requestId)) return;
_state = Failed(e);
}
notifyListeners();
}
bool _isStale(int requestId) => _disposed || requestId != _requestId;
@override
void dispose() {
_disposed = true;
super.dispose();
}
}Three details matter here.
- Every path assigns a state and notifies once. The
tryblock and thecatchblock each set_state, and the singlenotifyListeners()after them runs for both. There is nofinallyto forget, because there is no separate loading flag to reset. _requestIdidentifies the latest call. Each call toload()takes a new number. When an older request finishes after a newer one, its number no longer matches and the result is dropped. Without this check, a slow first response can overwrite the fresh data from a second call._disposedprevents a late notification. A request can finish after the screen is gone.
Reading the state in the view
The view switches over the state. Because LoadState is sealed, the compiler reports an error if you leave out a case, and it will also report one if you add a new subclass later and forget to update a screen.
import 'package:flutter/material.dart';
class TodoBody extends StatelessWidget {
const TodoBody({super.key, required this.viewModel});
final TodoListViewModel viewModel;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: viewModel,
builder: (context, _) => switch (viewModel.state) {
Loading() => const Center(child: CircularProgressIndicator()),
Failed(:final error) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Something went wrong: $error'),
FilledButton(
onPressed: viewModel.load,
child: const Text('Retry'),
),
],
),
),
Loaded(:final data) => ListView(
children: [for (final todo in data) ListTile(title: Text(todo.title))],
),
},
);
}
}The retry button calls viewModel.load directly. The view does not change any state itself. It reports the user's intent, and the view model decides what happens next.
Showing technical errors to users
The view above prints $error, which is fine while you develop but poor for real users. A raw exception message such as SocketException: Failed host lookup means nothing to most people. It can also expose internal details.
A better design maps exceptions to user-facing messages in one place. Keep the raw Object in Failed for logging, and add a small function, or a field on Failed, that turns it into text. The view then shows the friendly text and the retry button.
Refreshing without losing data
A full-screen spinner is correct for the first load. It is a poor choice for a refresh, because the list the user was reading disappears. You have two common options:
- Add a separate
isRefreshingflag next to_state, and leave_stateasLoadedwhile the refresh runs. - Give
Failedan optionalpreviousfield that holds the last good data, so the view can show the list with an error banner on top.
Both options add a second piece of state. Add them only when the screen needs them. A first-load spinner is enough for many screens, and extra states are more code to test.
Actions that change data
toggle also does asynchronous work, and it can fail. Decide whether an action failure should replace the whole screen. For a todo list, a failed toggle usually should not swap the list for an error page. Surface it another way, such as a one-time message field that the view shows in a SnackBar and then clears. If a failed action should show an error page, set _state = Failed(e) in its catch block, and use the same _isStale check after each await.
Testing the transitions
Because the state is one value, a test can assert on it directly. The following test controls when each fetch finishes, and it proves that the late first response is ignored. Import your app's Todo, TodoRepository, and TodoListViewModel files at the top of the test file.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
class ControlledRepository implements TodoRepository {
final List<Completer<List<Todo>>> completers = [];
@override
Future<List<Todo>> fetchTodos() {
final completer = Completer<List<Todo>>();
completers.add(completer);
return completer.future;
}
@override
Future<void> setDone(int id, bool done) async {}
}
void main() {
test('a late result from an older load is ignored', () async {
final repository = ControlledRepository();
final vm = TodoListViewModel(repository: repository);
final first = vm.load();
final second = vm.load();
repository.completers[1].complete([const Todo(id: 2, title: 'new')]);
await second;
repository.completers[0].complete([const Todo(id: 1, title: 'old')]);
await first;
final state = vm.state;
expect(state, isA<Loaded<List<Todo>>>());
expect((state as Loaded<List<Todo>>).data.single.title, 'new');
});
}Common errors
- Forgetting to leave
Loading. If a code path returns early without assigning a state, the spinner never goes away. Every branch ofload()must either assign a state or return because the result is stale. - Swallowing the exception. A
catchthat sets no state leaves the view stuck inLoading. - Returning early in the wrong place. A stale check that skips
notifyListeners()is correct for stale results, but only for them. Do not use the same early return for ordinary failures. - Starting a load inside
build. Callload()frominitStateor from a provider'screate, not frombuild, or every rebuild starts a new request.
Exercise
A user taps Retry twice quickly. The first request fails after 5 seconds and the second succeeds after 1 second. With the _requestId check in load(), what does the view show at the end, and what would it show without the check?
Show answer
With the check, the second request succeeds first and sets Loaded. When the first request fails at 5 seconds, its id no longer matches _requestId, so the catch block returns early and the view stays on Loaded. Without the check, the first request's catch block would set Failed and overwrite the good data, so the user would see an error even though the latest request succeeded.