Sub topic 8
Building a view model on ChangeNotifier
A view model holds the state a screen needs and the actions the screen can trigger. This chapter builds one from scratch on ChangeNotifier, using the todo example from the rest of the tutorial. It assumes you know Dart classes, async/await, Future, and the difference between StatelessWidget and StatefulWidget. It also assumes you have used setState and have seen it get unwieldy.
What a view model is responsible for
In MVVM, the view model sits between the view (widgets) and the data layer (repositories). It has three jobs:
- Hold the UI state: the data and flags the screen needs to draw itself.
- Expose actions: methods the view calls when the user does something.
- Notify listeners: tell the view when the state has changed.
A view model does not build widgets and does not import package:flutter/material.dart. It only needs package:flutter/foundation.dart, which provides ChangeNotifier. That restriction keeps it testable as plain Dart.
The data layer the view model depends on
The view model needs a model and a repository to talk to. These come from earlier chapters. Here is the model and the repository interface with an in-memory implementation.
class Todo {
const Todo({required this.id, required this.title, this.done = false});
final int id;
final String title;
final bool done;
Todo copyWith({String? title, bool? done}) =>
Todo(id: id, title: title ?? this.title, done: done ?? this.done);
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
class InMemoryTodoRepository implements TodoRepository {
final List<Todo> _todos = [
const Todo(id: 1, title: 'Write the view model'),
const Todo(id: 2, title: 'Connect the view'),
];
@override
Future<List<Todo>> fetchTodos() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return List.unmodifiable(_todos);
}
@override
Future<void> setDone(int id, bool done) async {
final index = _todos.indexWhere((t) => t.id == id);
if (index == -1) throw ArgumentError('Unknown todo $id');
_todos[index] = _todos[index].copyWith(done: done);
}
}The view model will depend on the TodoRepository interface, not on InMemoryTodoRepository. That choice is what lets you swap in a fake during tests.
Writing the view model
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;
List<Todo> get todos => _todos;
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> toggle(Todo todo) async {
try {
await _repository.setDone(todo.id, !todo.done);
_todos = await _repository.fetchTodos();
_error = null;
} catch (e) {
_error = e;
}
notifyListeners();
}
}Walk through the design choices one at a time.
Private fields, public getters
The fields _todos, _isLoading, and _error are private. The view reads them only through getters. This means only the view model can change state, so every change passes through code that can call notifyListeners. If the view could assign vm.todos = [] directly, it could change state without any notification and the screen would go stale.
The list itself also matters. _todos is replaced with a new list on each fetch and never mutated in place. The repository returns List.unmodifiable, so a view that tries vm.todos.add(...) gets a runtime error instead of silently corrupting state.
The constructor takes the repository
TodoListViewModel receives its repository as a required named parameter. It never creates one itself. This is constructor injection, covered fully in a later chapter. For now, note the effect: the same view model class works with the in-memory repository, a network-backed one, or a test fake.
The notify pattern in load()
load() follows a pattern you will repeat in most view model methods:
- Set the state to "working" and call
notifyListeners()so the view shows a spinner. - Do the asynchronous work inside
try. - Store a failure in
_errorinsidecatch. - Reset the loading flag in
finallyand callnotifyListeners()once more.
Putting the second notifyListeners() in finally guarantees the view leaves the loading state on both success and failure. If it were only in the try block, a thrown exception would leave the spinner on forever.
Clearing _error = null at the start matters too. Without it, a retry after a failure would keep showing the old error until the new request finished.
Notify after changes, not before
notifyListeners() runs listeners synchronously. A listener typically schedules a rebuild, and the rebuild reads the getters. So the fields must already hold their new values when you call it. Calling notifyListeners() first and then assigning would show the view stale data.
You also do not need to notify after every single assignment. In load(), the first notifyListeners() covers two changes (_isLoading and _error). Batch related assignments, then notify once.
How ChangeNotifier delivers the notification
ChangeNotifier keeps a list of listener callbacks. addListener adds one, removeListener removes one, and notifyListeners calls each in turn. It does not compare old and new state. Calling notifyListeners() always notifies, even if nothing changed. That makes redundant calls cheap in correctness terms but wasteful in rebuilds.
Handling actions: the toggle method
toggle shows a second pattern. It calls setDone on the repository, then re-fetches the list so the view model's state matches the repository's. The repository stays the single source of truth, and the view model never edits _todos by hand.
This version has no loading flag, so the checkbox updates only after both calls finish. That is the simplest correct behavior. Optimistic updates, where the UI changes first and rolls back on failure, are possible but add state to manage.
Notice that toggle has a single notifyListeners() at the end, outside the try/catch. It runs on both paths, because both paths changed state: success replaced _todos, and failure set _error.
Edge cases to know about
Overlapping calls
Nothing stops the user from calling load() twice before the first call finishes. Both calls run, and whichever finishes last writes _todos. The first one to finish also sets _isLoading = false while the second is still running. If that matters for your screen, guard it:
Future<void> load() async {
if (_isLoading) return;
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
}Notifying after disposal
If the screen is closed while a request is in flight, the view model may be disposed before the await returns. Calling notifyListeners() on a disposed ChangeNotifier throws an error in debug mode. A later chapter covers lifecycle in detail. The short version: whoever creates the view model disposes it, and long-running methods may need to check a flag before notifying.
Errors as `Object?`
The example stores the raw exception in _error. That is fine for a first version, but the view then prints $error, which can expose technical text to the user. In a real app, map failures to a message or a small error type inside the view model.
Empty versus not loaded
_todos starts as const []. An empty list can mean "not loaded yet" or "loaded, nothing there". The view tells these apart using isLoading and error, so keep those flags accurate.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Forgetting `notifyListeners()` | The screen does not update | Notify after every state change |
| Notifying before assigning | The view reads stale values | Assign first, then notify |
| Mutating `_todos` in place and notifying | Works until something compares lists by identity | Replace the list with a new one |
| Importing `material.dart` in the view model | Hard to test without Flutter widgets | Import only `foundation.dart` |
| Creating the repository inside the view model | Cannot be replaced in tests | Pass it through the constructor |
| Leaving `_isLoading = true` on error | Spinner never stops | Reset it in `finally` |
A quick check on a view model without Flutter widgets
Because the view model only depends on foundation.dart and an interface, you can run it with no widget tree. This small main shows the notification behavior directly.
import 'package:flutter/foundation.dart';
class CounterViewModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() {
final vm = CounterViewModel();
vm.addListener(() => print('count is now ${vm.count}'));
vm.increment();
vm.increment();
vm.dispose();
}Running it prints count is now 1 and then count is now 2. The listener runs synchronously inside each increment(). The final dispose() removes all listeners. After it, calling increment() would throw in debug mode, which is the disposal pitfall in miniature.
Exercise
In TodoListViewModel.load(), why is the second notifyListeners() placed in the finally block instead of at the end of the try block?
Show answer
A finally block runs whether the try succeeds or throws. Placing the call there means the view is always told that loading has ended, so the spinner stops on both success and failure. If it were only at the end of try, an exception from fetchTodos() would skip it, _isLoading would be reset only in a block that never ran its notification, and the view would keep showing the loading indicator.
Exercise
A teammate adds a method void clearAll() { _todos.clear(); } to the view model, and the screen does not update. Name two problems with this code and give a corrected version.
Show answer
First, it never calls notifyListeners(), so listeners are not told anything changed. Second, it mutates the existing list in place. _todos may hold an unmodifiable list returned by the repository, so clear() can throw, and in-place mutation hides changes from code that compares list identity. A corrected version is void clearAll() { _todos = const []; notifyListeners(); }. If the todos should also be removed from the data source, the method should call the repository and then refresh _todos from it.