Sub topic 14
Creating and disposing view models safely
This chapter covers who creates a view model, who disposes it, and what goes wrong when the two answers are unclear. It assumes you know Dart async/await, StatefulWidget lifecycle methods (initState, dispose), and the TodoListViewModel and TodoRepository from the earlier chapters. The provider package is used in one section.
Why lifecycle matters for view models
A ChangeNotifier keeps a list of listeners. Each ListenableBuilder or Consumer adds itself to that list when it mounts and removes itself when it unmounts. The view model usually outlives none of them. It also often holds its own resources: pending futures, stream subscriptions, timers.
Two failure modes follow from this:
- Leaks. Nobody calls
dispose, so subscriptions and timers keep running after the screen is gone. - Use after dispose. An async call finishes after
dispose, then callsnotifyListenerson a dead object. In debug builds Flutter throws an error such as "A TodoListViewModel was used after being disposed."
The fix is a clear rule: whoever creates the view model disposes it. The rest of the chapter applies that rule.
Ownership options
| Owner | Creates it | Disposes it | Use when |
|---|---|---|---|
| `State` of a `StatefulWidget` | `initState` | `dispose` | You use plain `ListenableBuilder`, or no DI package. |
| `ChangeNotifierProvider(create:)` | The `create` callback | Automatically | You already use `provider`. This is the common choice. |
| `ChangeNotifierProvider.value` | Someone else | Not disposed | The view model lives longer than this subtree, for example an app-wide one. |
Owning the view model in a State object
Create the view model once in initState and dispose it in dispose. The widget receives the repository, not the view model.
import 'package:flutter/material.dart';
class TodoScreen extends StatefulWidget {
const TodoScreen({super.key, required this.repository});
final TodoRepository repository;
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
late final TodoListViewModel _viewModel;
@override
void initState() {
super.initState();
_viewModel = TodoListViewModel(repository: widget.repository)..load();
}
@override
void dispose() {
_viewModel.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: ListenableBuilder(
listenable: _viewModel,
builder: (context, _) {
if (_viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final todo in _viewModel.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => _viewModel.toggle(todo),
),
],
);
},
),
);
}
}Calling load() from initState is safe for notifications. No listener exists yet, so the first notifyListeners reaches nobody. The ListenableBuilder builds afterwards and reads the current state.
Never create the view model in build
build can run many times: on every parent rebuild, theme change, or MediaQuery change. A view model created there is replaced each time, and its state and in-flight loads go with it.
// Wrong: a new view model, and a new load, on every rebuild.
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: TodoListViewModel(repository: widget.repository)..load(),
builder: (context, _) => const SizedBox(),
);
}The replaced view models are never disposed either. If you see a loading spinner that flashes whenever something nearby changes, check for this first.
Letting Provider own it
ChangeNotifierProvider calls create once, keeps the instance, and calls dispose when the provider leaves the tree.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class TodoPage extends StatelessWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) =>
TodoListViewModel(repository: context.read<TodoRepository>())..load(),
child: Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: Consumer<TodoListViewModel>(
builder: (context, vm, _) => ListView(
children: [
for (final todo in vm.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => vm.toggle(todo),
),
],
),
),
),
);
}
}Use context.read inside create. It reads the repository once and does not subscribe. context.watch there would be a mistake because create does not re-run.
The provider creates the view model lazily, on first read. Here Consumer reads it right away, so load() starts at once. If a view model should start work even before something reads it, pass lazy: false.
create versus value
// Wrong: a new instance is created here, but the provider never disposes it.
ChangeNotifierProvider.value(
value: TodoListViewModel(repository: repository),
child: const TodoList(),
);.value assumes the object already exists and belongs to someone else, so it does not dispose it. Creating an instance inside .value therefore leaks it, and a rebuild may create another. Use .value only for an existing instance with a longer lifetime. Use create for everything else.
Late results after dispose
Even with correct ownership, a race remains. The user opens the screen and leaves before fetchTodos finishes. The widget disposes the view model, then the future completes and load reaches notifyListeners.
Without a guard, the last step throws in debug builds. Add the guard once, in a mixin, so every view model can reuse it.
import 'package:flutter/foundation.dart';
mixin SafeNotifier on ChangeNotifier {
bool _disposed = false;
bool get isDisposed => _disposed;
@override
void notifyListeners() {
if (_disposed) return;
super.notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
class TodoListViewModel extends ChangeNotifier with SafeNotifier {
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();
}
}
}The load body is the same as before. The only change is that notifyListeners now ignores calls after disposal. After an await, you can also check isDisposed and skip the remaining work, which matters if the code after the await does something costly.
Disposing what the view model owns
If the view model starts a timer or subscribes to a stream, it must stop them in dispose. Release your own resources first and call super.dispose() last.
import 'dart:async';
import 'package:flutter/foundation.dart';
class ClockViewModel extends ChangeNotifier {
ClockViewModel() {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
_now = DateTime.now();
notifyListeners();
});
}
late final Timer _timer;
DateTime _now = DateTime.now();
DateTime get now => _now;
@override
void dispose() {
_timer.cancel();
super.dispose();
}
}Cancelling the timer first means no tick can fire between super.dispose() and the cancel. Without the cancel, the timer would keep calling notifyListeners on a disposed object forever.
Do not dispose the repository from the view model. The view model received it from outside, so the creator of the repository disposes it. Applying the ownership rule to every object keeps this clear.
Common errors
- "Used after being disposed". An async callback or timer outlived the view model. Apply the guard and cancel timers and subscriptions in
dispose. - Disposing twice. A widget disposes a view model that a provider also disposes. Pick one owner.
- Disposing a shared view model. A screen disposes an instance that another screen still uses. Give the instance to an owner with the longer lifetime and pass it down with
.value. - State lost on rebuild. The view model is created in
build, or the provider'screateis moved into a widget that is rebuilt with a new key. Move creation toinitStateor a stable provider. - Hot reload does not re-run
initState. After you change creation code, use hot restart to see the effect.
Exercise
A screen calls ChangeNotifierProvider.value(value: TodoListViewModel(repository: repo), child: ...) inside its build method. Name two problems and give the fix.
Show answer
The view model is created on every rebuild, so state and loads reset, and .value never disposes it, so each replaced instance leaks. Use ChangeNotifierProvider(create: ...), which creates the instance once and disposes it, or create the view model once in initState and dispose it in dispose.
Exercise
In ClockViewModel.dispose, why is _timer.cancel() called before super.dispose() and not after?
Show answer
The view model should release its own resources before the base class marks it disposed. If the timer fired between the two calls, it would call notifyListeners on an object that is already disposed. Cancelling first leaves no window for that.