Sub topic 16
Pitfalls and when MVVM is too much
This chapter assumes you have read the earlier chapters and have the Todo model, the TodoRepository interface, and TodoListViewModel in front of you. It also assumes you are comfortable with async/await, ChangeNotifier, and Provider. Here you will learn the mistakes that most often break MVVM code in Flutter, and how to decide when the pattern costs more than it gives.
Pitfalls that cause bugs
Calling notifyListeners after dispose
A view model is disposed when its screen leaves the tree. If a Future is still running at that moment, the code after await runs on a disposed object. In debug mode, calling notifyListeners on a disposed ChangeNotifier throws an assertion error, so you see this failure on slow networks or when users navigate quickly.
The fix is to track disposal and skip the notification:
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;
bool _disposed = false;
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();
}
}
@override
void notifyListeners() {
if (!_disposed) super.notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}Overriding notifyListeners once covers every method in the class. Use this guard when a view model does network work. A view model with only synchronous methods does not need it.
Creating the view model inside build
build can run many times per second during animations. A view model constructed there is recreated each time, so it loses its state and fires a new load() on every rebuild.
// Wrong: a new view model, and a new request, on every rebuild.
@override
Widget build(BuildContext context) {
final vm = TodoListViewModel(repository: context.read<TodoRepository>())
..load();
return TodoList(viewModel: vm);
}Create the view model once, in a place that runs once. ChangeNotifierProvider(create: ...) does this, and it also disposes the view model for you. A StatefulWidget can do the same in initState and dispose.
Disposal ownership
Whoever creates the view model must dispose it. ChangeNotifierProvider(create: ...) owns what it creates. ChangeNotifierProvider.value does not dispose anything, because it assumes someone else owns the object. Mixing these up gives you either a leak (nobody disposes) or a crash (two places dispose).
| Situation | Who disposes |
|---|---|
| `ChangeNotifierProvider(create: ...)` | The provider |
| `ChangeNotifierProvider.value(value: vm)` | Your own code |
| View model created in `State.initState` | `State.dispose` |
| View model passed in through a constructor | The creator, not the receiver |
Business logic in widgets
If a widget decides which todos are overdue, formats prices, or calls the repository directly, you can no longer test that logic without pumping widgets. Move it into the view model and expose the result as a getter. The widget should only read state and forward events.
Leaking mutable state
A getter that returns the private list lets any widget call add or remove on it. The view model's state then changes without a notification, and the screen shows stale data.
import 'dart:collection';
List<Todo> get todos => UnmodifiableListView(_todos);A mutation attempt now throws immediately instead of silently desynchronizing the UI. Replacing the whole list on each change, as the earlier chapters did, is the safer habit.
Passing BuildContext into a view model
A view model that takes a BuildContext to show a snackbar or navigate is tied to the widget tree. It cannot be tested as plain Dart, and the context may be unmounted by the time an await finishes. Expose the outcome as state instead, for example an error field, and let the view react to it.
Out-of-order async results
If the user pulls to refresh twice, two requests run at once and the slower one may finish last, overwriting newer data. A generation counter discards stale results:
int _loadGeneration = 0;
Future<void> load() async {
final generation = ++_loadGeneration;
_isLoading = true;
_error = null;
notifyListeners();
try {
final result = await _repository.fetchTodos();
if (generation != _loadGeneration) return;
_todos = result;
} catch (e) {
if (generation != _loadGeneration) return;
_error = e;
}
_isLoading = false;
notifyListeners();
}An early return inside try is why this version drops the finally block used earlier. A stale call must not touch _isLoading, because a newer call still owns that flag.
Rebuilding too much
A single notifyListeners rebuilds every listener. On a large screen, one changed field can rebuild widgets that do not use it. If profiling shows a problem, wrap only the part that needs the data in a smaller Consumer, or use Selector to rebuild only when a chosen value changes:
Selector<TodoListViewModel, int>(
selector: (context, vm) => vm.todos.where((t) => !t.done).length,
builder: (context, remaining, _) => Text('$remaining left'),
)Do not add Selector everywhere in advance. Measure first.
Other common slips
- Calling
context.watchin a callback such asonPressed. Usecontext.readthere, becausewatchis only forbuild. - Constructing the repository inside the view model. This blocks injection, so tests cannot substitute a fake.
- Forgetting to reset
_errorwhen a retry starts, so an old error message stays on screen beside the spinner. - Skipping
notifyListenersafter a state change, so the UI never updates.
When MVVM is too much
MVVM adds files, interfaces, and indirection. That cost pays off when logic is non-trivial, when data comes from outside the widget, or when several screens share it. It does not pay off for every piece of state.
Use plain setState or a local controller when all of these hold:
- The state belongs to one widget, such as a toggle, a selected tab, or an animation value.
- No I/O or business rules are involved.
- Nothing outside that widget needs to read or test it.
A text field's TextEditingController and an expanded/collapsed flag are typical examples. Putting them in a view model adds ceremony without making anything easier to test.
The repository layer can also be overbuilt. If a repository only forwards each call to one service, with no caching, mapping, or merging of sources, it is a pass-through. In a small app you may call the service directly from the view model. Keep the interface if you want to fake it in tests, and add the full layer when a second data source or a cache appears.
Review checklist
Before shipping a screen, check these points:
- The view model is created once, by an owner that also disposes it.
- Async methods cannot notify after disposal or apply stale results.
- State is exposed read-only, and the UI changes only through view model methods.
- No
BuildContextappears in the view model. - Dependencies arrive through the constructor.
- The view model has at least a success test and a failure test using a fake repository.
Exercise
A screen shows a spinner and then throws "A TodoListViewModel was used after being disposed" when the user presses back during loading. The view model is created with ChangeNotifierProvider(create: ...). What is wrong, and how do you fix it?
Show answer
The provider correctly disposes the view model when the screen is removed, but the pending load() still runs notifyListeners after await completes. Override notifyListeners to skip the call once a _disposed flag, set in dispose, is true. The provider is not at fault, so do not switch to .value.
Exercise
A settings screen has a single switch that toggles a "compact mode" flag. The flag is read only by that screen, is not saved, and needs no network call. Should you create a view model and repository for it? Explain.
Show answer
No. The state is local to one widget and involves no I/O or business rules, so setState in a StatefulWidget is enough. A view model and repository would add files without improving testability. Add them later if the setting must be saved, shared across screens, or tested as logic.