Sub topic 11
User actions flow in, state flows out
This chapter assumes you have built a view model on ChangeNotifier and rebuilt a view with ListenableBuilder, as in the earlier chapters. It also assumes you know Future, async/await, and the Todo and TodoRepository types from the running todo example.
The rule for this chapter is that events travel from the view to the view model, and state travels from the view model to the view. Nothing travels the other way. This is called unidirectional data flow.
The two directions
The view is a function of state. Given the same view model state, it should build the same widgets. The view never edits that state. When the user taps something, the view reports the tap by calling a method on the view model. The view model decides what the tap means, talks to the repository, updates its own fields, and calls notifyListeners(). The view then rebuilds from the new state.
Here is the same idea as a diagram.
The view has no reference to the repository. The repository has no reference to the view. The view model sits between them and is the only place where an action becomes a state change.
Why one direction matters
Two-way flow means that several parts of the program can change the same value. Then a wrong value on screen could come from any of them, and you have to search all of them. With one direction, every state change goes through a view model method. To find out why the screen shows something, you read that method.
You also get a single place to enforce rules. If a todo must not be toggled while another toggle is in flight, you write that check once in toggle, not in every widget that has a checkbox.
What the view may and may not do
| The view may | The view may not |
|---|---|
| Read getters such as `todos`, `isLoading`, `error` | Assign to view model fields or mutate the lists it returns |
| Call view model methods from callbacks such as `onChanged` | Call the repository or a service directly |
| Hold purely visual state, such as a `TextEditingController` or scroll position | Copy view model data into its own `State` fields and keep editing the copy |
| Rebuild when notified | Decide business rules, such as which todos count as finished |
Purely visual state that no other part of the app cares about can stay in the widget. A text field's controller is a typical example. When the user presses "Save", the view reads the controller's text and passes it to a view model method as an argument. The state still flows out and the action still flows in.
Protecting the state from the view
Dart cannot stop a widget from calling vm.todos.add(...) if the getter returns the private mutable list. The widget would change the data without any notification, so the screen and the view model would disagree.
Return a read-only view of the list. UnmodifiableListView wraps the list without copying it, and any mutation attempt throws.
import 'dart:collection';
import 'package:flutter/foundation.dart';
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
// Read-only state going out.
UnmodifiableListView<Todo> get todos => UnmodifiableListView(_todos);
bool get isLoading => _isLoading;
Object? get error => _error;
// Actions coming in.
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
}
void dismissError() {
if (_error == null) return;
_error = null;
notifyListeners();
}
}The fields are private and every change happens inside a method that ends with notifyListeners(). Because Todo is immutable, a widget also cannot change a todo in place. It can only ask for a change.
dismissError shows that an action does not have to touch the repository. Any user intent that changes state belongs in the view model, even when it is trivial.
Actions that run on the repository
The toggle method from the earlier chapter waits for the repository, fetches the list again, and then notifies. This is simple and always consistent with the source of truth. The cost is a visible delay between the tap and the checkbox changing.
An optimistic update changes the state first and then asks the repository. If the repository fails, the view model restores the earlier state.
Future<void> toggle(Todo todo) async {
final previous = _todos;
final newValue = !todo.done;
_todos = [
for (final t in previous)
t.id == todo.id ? t.copyWith(done: newValue) : t,
];
_error = null;
notifyListeners();
try {
await _repository.setDone(todo.id, newValue);
} catch (e) {
_todos = previous;
_error = e;
notifyListeners();
}
}The flow is still one-directional. The view only calls toggle. The new state arrives through a notification, and a failure arrives through the same error getter as any other failure.
This version has edge cases you should know about:
- Overlapping actions. If the user toggles two different todos quickly and the first call fails,
_todos = previousalso discards the second todo's change. For a small list you can reload withload()after a failure instead of restoring a snapshot. - Stale arguments. The method uses the
todoobject the view passed in. If the view was built from older state,!todo.donemay be wrong. Passing theidand reading the current value from_todosavoids this. - Repeated taps. Nothing stops the user from tapping the same checkbox again before the first call finishes. A guard flag or a command object can reject the second call. The commands chapter covers that.
Wiring the view for one-way flow
The view below only reads state and only calls methods. It shows a dismissible error banner above the list instead of replacing the whole screen, so the user can keep working.
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, _) {
if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
return Column(
children: [
if (viewModel.error != null)
MaterialBanner(
content: Text('Something went wrong: ${viewModel.error}'),
actions: [
TextButton(
onPressed: viewModel.dismissError,
child: const Text('Dismiss'),
),
],
),
Expanded(
child: ListView(
children: [
for (final todo in viewModel.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => viewModel.toggle(todo),
),
],
),
),
],
);
},
);
}
}CheckboxListTile is a controlled widget. Its value always comes from todo.done. When the user taps it, the tile does not keep its own checked state. It calls onChanged, and the box only changes once the view model notifies and the list rebuilds with a new todo.done. If the view model rejects the action, the checkbox stays where it was.
Common mistakes
- Passing a callback that writes state. A callback such as
onChanged: (v) => vm.todos[0] = ...cannot compile against a read-only getter, which is the point. Keep the getter read-only so the compiler catches this. - Calling the repository from the widget. The result then never reaches the view model, so other widgets observing it stay out of date.
- Mutating state without notifying. If a method changes a field and forgets
notifyListeners(), the view silently shows old data. Make it a habit to end every state-changing method with one call. - Notifying inside
build. Calling an action frombuildtriggers a notification during a build, which Flutter reports as an error. Start work frominitState, a callback, or a provider'screate.
Exercise
A teammate's widget has a bool _checked field in its State, set from onChanged with setState, and it also calls viewModel.toggle(todo) in the same callback. Which direction rule does this break, and what happens if the repository call fails?
Show answer
It breaks the rule that state flows only from the view model to the view, because the widget keeps a second copy of the state and changes it itself. If setDone fails, the view model keeps done at its old value (or restores it after an optimistic update), but the widget's _checked has already changed. The checkbox then shows a value that the source of truth does not have. The fix is to delete _checked and set value: todo.done so the view always reads the view model.
Exercise
Why does UnmodifiableListView<Todo> get todos help enforce one-way flow, and why is it not enough on its own?
Show answer
It makes it impossible for a widget to add to or remove from the list without going through the view model, because any attempt throws. It is not enough on its own because it protects only the list. A view model that exposes a mutable object, or a public field, still lets widgets change state silently. Todo also needs to be immutable, with final fields, and the other fields must be private and exposed through getters.