Sub topic 16
Pitfalls and When MVVM Is Too Much
This chapter assumes you know Dart classes, async and await, Flutter widget lifecycles, and the basic roles of views, view models, and repositories.
MVVM helps when a screen has asynchronous work, reusable state, or several user actions. It also adds classes, wiring, and lifecycle decisions. Use it to separate responsibilities, not as a rule that every widget needs a view model.
Avoiding lifecycle errors
A view model can outlive an asynchronous operation. For example, a user may leave a screen while load() is waiting for a network response. If the operation completes and calls notifyListeners(), the view model might already be disposed.
Track disposal and check it before changing state or notifying listeners:
import 'package:flutter/foundation.dart';
abstract class TodoRepository {
Future<List<String>> fetchTitles();
}
class TodoViewModel extends ChangeNotifier {
TodoViewModel(this._repository);
final TodoRepository _repository;
List<String> _titles = const [];
bool _loading = false;
bool _disposed = false;
List<String> get titles => _titles;
bool get loading => _loading;
Future<void> load() async {
if (_disposed) return;
_loading = true;
notifyListeners();
try {
final result = await _repository.fetchTitles();
if (_disposed) return;
_titles = List.unmodifiable(result);
} finally {
if (_disposed) return;
_loading = false;
notifyListeners();
}
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}The view model owns the _disposed flag because it owns its lifecycle. Provider usually disposes a view model created with its create callback. Do not manually dispose that same instance from the widget.
Preventing stale asynchronous results
Two loads can overlap. A slower first request might finish after a newer request and overwrite newer data. A request token prevents old work from applying its result:
int _requestNumber = 0;
Future<void> reload() async {
final request = ++_requestNumber;
final result = await _repository.fetchTitles();
if (_disposed || request != _requestNumber) return;
_titles = List.unmodifiable(result);
notifyListeners();
}Use cancellation when the service supports it. Otherwise, ignoring stale results is often sufficient.
Keeping responsibilities clear
Widgets should describe layout and forward events. They should not decide business rules, transform API responses, or call several services directly. Put those decisions in the view model or repository.
The repository owns data access. The view model converts that data into state the view can render. Keep state immutable from the view’s perspective. Expose read-only getters and replace collections instead of allowing widgets to mutate internal lists.
Common warning signs include:
build()contains business rules or starts network requests.- The view model contains
TextEditingControllerobjects only used by one widget. - The repository returns widgets or
BuildContext. - Several view models duplicate the same loading and error logic.
- A small static screen has multiple classes with no meaningful behavior.
When MVVM is too much
For a screen with one local value and one button, StatefulWidget with setState may be clearer. MVVM becomes useful when state must survive widget rebuilds, asynchronous operations need testing, or multiple views share the same behavior.
| Situation | Practical choice |
|---|---|
| One field and local interaction | `StatefulWidget` and `setState` |
| Async data with loading and errors | View model and repository |
| Shared state across screens | Injected view model or another state solution |
| Complex reusable business rules | View model plus tested domain or service code |
Choose the smallest structure that keeps the code understandable and testable.
Exercise
A view calls a repository directly from its onPressed callback and then updates several fields with setState. What is the main design problem, and where should the work move?
Show answer
The view owns business and data-access logic. Move the repository call and state decisions into a view model, then let the view forward the tap and render the view model's state.