Sub topic 3
User actions flow in, state flows out
This chapter assumes you know Dart classes and async/await, can build widgets with ListenableBuilder or Provider, and have a view model that extends ChangeNotifier from the earlier chapters.
Actions go in, state comes out
A view sends user actions to the view model. The view model changes its state, then calls notifyListeners(). The view reads the new state and rebuilds. Data never flows back from the view into the state.
Injecting repositories into view models
Pass the repository in through the constructor. The view model then depends on the TodoRepository interface, not a concrete class, so a test can supply a different implementation.
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
// state and methods follow
}Unit testing a view model with a fake repository
A fake is a simple class that implements the same interface and returns canned data. Test the view model as plain Dart, with no widgets.
import 'package:flutter_test/flutter_test.dart';
class FakeTodoRepository implements TodoRepository {
FakeTodoRepository(this.todos);
List<Todo> todos;
@override
Future<List<Todo>> fetchTodos() async => List.of(todos);
@override
Future<void> setDone(int id, bool done) async {
todos = [for (final t in todos) t.id == id ? t.copyWith(done: done) : t];
}
}
void main() {
test('toggle flips the done flag', () async {
final vm = TodoListViewModel(
repository: FakeTodoRepository([const Todo(id: 1, title: 'A')]),
);
await vm.load();
await vm.toggle(vm.todos.first);
expect(vm.todos.first.done, isTrue);
});
}Creating and disposing view models safely
Create a view model where it is needed and let the owner dispose it. ChangeNotifierProvider does this for you. If you create the view model yourself in a StatefulWidget, call dispose() on it in the state's dispose method.
> Calling notifyListeners() after dispose() throws an error. Cancel or ignore pending async work before disposing.
Wrapping actions in command objects
A command object wraps one action and tracks whether it is running and whether it failed. Use one when a button must be disabled during a request, or when the same action runs from several places. For a single simple toggle, a plain method on the view model is enough.
Pitfalls and when MVVM is too much
- Putting business rules in widgets. Move them to the view model or repository.
- Forgetting
notifyListeners()after a state change, so the screen stays stale. - Exposing mutable lists. Return
List.unmodifiableor a copy. - Using MVVM for a screen with one widget and no shared state. A
StatefulWidgetwithsetStateis simpler there.
Exercise
A toggle call changes the repository but the screen does not update. Name the most likely missing line in the view model.
Show answer
The view model did not call notifyListeners() after updating its _todos field, so listeners were never told the state changed.