Sub topic 14
Creating and Disposing View Models Safely
Assume you know Dart classes, async and await, Flutter widget lifecycles, and the difference between setState and a ChangeNotifier. This chapter focuses on ownership: deciding who creates a view model and who must dispose of it.
A view model has an owner
A view model can hold resources that need cleanup:
Timerobjects- stream subscriptions
- animation controllers
- database or socket listeners
- asynchronous work that may finish later
ChangeNotifier.dispose() marks the notifier as unusable and releases its listener resources. After disposal, the view model must not call notifyListeners().
The code that creates a view model should normally dispose of it. This rule prevents both memory leaks and double disposal.
| How the view model is created | Usual owner | Where disposal happens |
|---|---|---|
| `ChangeNotifierProvider(create: ...)` | Provider | Provider automatically calls `dispose()` |
| In a `State` object | That `State` object | The state's `dispose()` method |
| Passed in from a parent | The creating parent | The original owner |
Guarding asynchronous work
An asynchronous repository call can finish after the screen has gone away. A safe view model records that it has been disposed and checks the flag before changing state.
import 'dart:async';
import 'package:flutter/foundation.dart';
abstract class TodoRepository {
Future<List<String>> fetchTodos();
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel(this._repository);
final TodoRepository _repository;
Timer? _refreshTimer;
var _disposed = false;
List<String> _todos = const [];
List<String> get todos => List.unmodifiable(_todos);
Future<void> load() async {
if (_disposed) return;
try {
final loadedTodos = await _repository.fetchTodos();
if (_disposed) return;
_todos = loadedTodos;
notifyListeners();
} catch (_) {
if (!_disposed) {
// Store an error state here, then notify listeners.
notifyListeners();
}
}
}
void startRefreshing() {
if (_disposed) return;
_refreshTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => load(),
);
}
@override
void dispose() {
_disposed = true;
_refreshTimer?.cancel();
super.dispose();
}
}The check after await matters. The view model could be disposed while fetchTodos() is waiting. Cancel timers and subscriptions before calling super.dispose().
Provider and manual ownership
When using the provider package, use create for a new view model:
ChangeNotifierProvider(
create: (context) => TodoListViewModel(
context.read<TodoRepository>(),
)..load(),
child: const TodoPage(),
)Provider owns this instance and disposes it when the provider leaves the widget tree. Use ChangeNotifierProvider.value when exposing an instance that already has an owner. Do not use .value to create a new view model during a build.
If a stateful widget creates the view model itself, dispose it in the matching lifecycle method:
class _TodoPageState extends State<TodoPage> {
late final TodoListViewModel viewModel;
@override
void initState() {
super.initState();
viewModel = TodoListViewModel(widget.repository);
}
@override
void dispose() {
viewModel.dispose();
super.dispose();
}
}Exercise
A screen creates a view model in initState, but the parent passes that same instance to another screen. Which screen should call dispose?
Show answer
The code that created and owns the instance should call dispose. A screen that only receives the instance must not dispose it unless ownership was explicitly transferred.