Sub topic 4
Designing the state a view needs
This chapter assumes you know Dart classes, async/await, StatefulWidget, and why setState gets hard to manage in larger widgets. It also assumes you have seen that a view model extends ChangeNotifier and calls notifyListeners. The focus here is the shape of the state a view model exposes, not the notification mechanics.
What "UI state" means
UI state is everything the view needs in order to draw itself, and nothing else. For a todo screen that includes the list to show, whether a load is running, whether it failed, and which filter is selected.
UI state is not the same as the data in your repository. The repository holds all todos. The screen may show only the unfinished ones, with a count in the header and an empty-state message when none match. Deciding where each of those values lives is the main design work in this chapter.
A useful test: the view's build method should read values and lay them out. If build contains where, fold, or if (a && !b || c) logic, that logic belongs in the view model as a named getter.
Three kinds of state
| Kind | Example | Where it lives | Stored or computed |
|---|---|---|---|
| Source state | The loaded list of todos, the selected filter, the loading flag, the last error | Private fields in the view model | Stored |
| Derived state | Visible todos, remaining count, "show empty message" | Public getters in the view model | Computed on read |
| Ephemeral state | Text typed in a field, scroll offset, animation progress | The widget's `State` or a controller | Stored in the widget |
The rule for source state is that each fact is stored once. The rule for derived state is that anything computable from source state is a getter, not a second field. The rule for ephemeral state is that if no other widget and no test cares about the value, keep it in the widget.
Why derived values should not be stored
Suppose you store _remainingCount as a field and update it in toggle. Now every method that changes _todos must also remember to update the count. Miss one, and the header disagrees with the list. This is a synchronization bug, and it appears only on the code path you forgot.
A getter cannot go stale:
int get remainingCount => _todos.where((t) => !t.done).length;The cost is that the getter runs on every read. For lists of tens or hundreds of items this is negligible. If profiling shows a real cost, cache the result and clear the cache in the one place that assigns _todos. Do that only with evidence.
A view model with designed state
This version is self-contained. It uses a trimmed TodoRepository with only fetchTodos and requires Dart 3 for the switch expression.
import 'package:flutter/foundation.dart';
class Todo {
const Todo({required this.id, required this.title, this.done = false});
final int id;
final String title;
final bool done;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
}
enum TodoFilter { all, active, completed }
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
// Source state: stored once, private.
List<Todo> _todos = const [];
TodoFilter _filter = TodoFilter.all;
bool _isLoading = false;
Object? _error;
// Read-only exposure of source state.
List<Todo> get todos => _todos;
TodoFilter get filter => _filter;
bool get isLoading => _isLoading;
Object? get error => _error;
// Derived state: computed from the fields above.
List<Todo> get visibleTodos => switch (_filter) {
TodoFilter.all => _todos,
TodoFilter.active =>
List.unmodifiable(_todos.where((t) => !t.done)),
TodoFilter.completed =>
List.unmodifiable(_todos.where((t) => t.done)),
};
int get remainingCount => _todos.where((t) => !t.done).length;
bool get showEmptyMessage =>
!_isLoading && _error == null && visibleTodos.isEmpty;
void setFilter(TodoFilter value) {
if (value == _filter) return;
_filter = value;
notifyListeners();
}
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = List.unmodifiable(await _repository.fetchTodos());
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
}
}Several choices here are deliberate.
- Private fields, public getters. The view can read
todosbut cannot assign it. The only way to change state is through a method such assetFilter, which also guarantees a notification. - Unmodifiable lists.
List.unmodifiableis applied once, when_todosis assigned. A view that callsvm.todos.add(...)gets anUnsupportedErrorimmediately, instead of silently changing state without a notification. - The guard in
setFilter. Returning early when the value is unchanged avoids a pointless rebuild. showEmptyMessageis named for what the view does. The view writesif (vm.showEmptyMessage)and does not repeat the three-part condition.
Exposing the minimum
Every public member is something the view can depend on, and every dependency is a thing you must keep stable. Prefer exposing what the screen displays. For example, a view that needs a label can read a String get summary getter, such as '3 left', instead of formatting from remainingCount in build. Formatting that depends on locale or widgets (dates with BuildContext, theme colors) is the exception. Keep it in the view, because the view model should not import package:flutter/material.dart.
Never expose the repository, a Future, or a Stream from the repository directly. That hands the view a way around the view model's state.
Impossible states
The view model above has an awkward corner. Nothing prevents _isLoading == true and _error != null at the same time, although the screen can show only one. The load method avoids it by clearing _error before setting the loading flag, but the type system does not enforce it. Each new method that touches these fields is another chance to break the rule.
You can reduce this in two ways.
- Keep all transitions in a few methods. Only
loadwrites_isLoadingand_error. This is cheap and works for small screens. - Replace the flags with one value. A single field of a sealed type such as loading, failure, or data cannot be loading and failed at once. The chapter on modeling loading and error states covers this approach.
For now, remember the check: list the combinations of your fields and ask which ones the screen cannot display.
Reading the state in the view
The view reads getters and does no computing:
Widget buildBody(TodoListViewModel vm) {
if (vm.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (vm.error != null) {
return Center(child: Text('Something went wrong: ${vm.error}'));
}
if (vm.showEmptyMessage) {
return const Center(child: Text('Nothing to show'));
}
return ListView(
children: [
for (final todo in vm.visibleTodos)
ListTile(
title: Text(todo.title),
trailing: Icon(todo.done ? Icons.check : Icons.circle_outlined),
),
],
);
}This function needs package:flutter/material.dart imported. Because build only branches on named getters, you can test every branch by testing the view model alone. Add a widget test only when you want to check that the layout matches.
Common mistakes
- Storing the same fact twice. A
_visibleTodosfield next to_todosand_filterwill drift out of sync. - Returning a mutable list. Without
List.unmodifiable, a widget can mutate the list in place and no listener hears about it. - Moving ephemeral state into the view model. A
TextEditingControllerorScrollControllerhas a lifecycle tied to a widget. Putting it in the view model makes disposal harder and tests heavier. - Calling
notifyListenerswithout a change. It is harmless to correctness but causes extra rebuilds. - Mutating fields outside the view model's methods. Public setters bypass notification. Keep the fields private.
Exercise
The todo screen needs a header reading "2 of 5 done". A teammate adds two fields, _doneCount and _totalCount, and updates them inside load and toggle. Describe what can go wrong, and rewrite the design so the header can never disagree with the list.
Show answer
The fields duplicate information already in _todos. Any code path that changes _todos without updating both counters, such as a future delete or add method, leaves the header wrong. Remove the two fields and add getters computed from _todos: int get totalCount => _todos.length;, int get doneCount => _todos.where((t) => t.done).length;, and optionally String get progressLabel => '$doneCount of $totalCount done';. The view reads progressLabel, and no method needs to remember to update it.
Exercise
Why does TodoListViewModel assign List.unmodifiable(...) to _todos, and what happens if a widget calls vm.todos.add(...)?
Show answer
Wrapping the list once at assignment makes the exposed list read-only, so the view cannot change state without going through a view model method that calls notifyListeners. Calling vm.todos.add(...) throws an UnsupportedError, which exposes the bug right away instead of producing a UI that silently fails to update.