Sub topic 3
How ChangeNotifier Notifies Listeners
This chapter assumes you know basic Dart classes, async and await, Flutter widget build methods, and the limits of managing shared state with setState.
ChangeNotifier is a Flutter class that implements Listenable. It lets an object keep state and notify registered listeners when that state changes. The class does not inspect your fields or compare old and new values. Your code decides when a change is meaningful.
The notification cycle
A view model usually follows this sequence:
A listener is a callback stored by the notifier. addListener registers it, and removeListener unregisters it. When notifyListeners() runs, the notifier calls its registered listeners synchronously.
import 'package:flutter/foundation.dart';
class CounterViewModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() {
final viewModel = CounterViewModel();
void printCount() {
print('Count: ${viewModel.count}');
}
viewModel.addListener(printCount);
viewModel.increment(); // Prints: Count: 1
viewModel.removeListener(printCount);
viewModel.dispose();
}The private _count field protects the state from direct modification. The count getter exposes the current value. increment changes the value first, then sends the notification.
A listener does not receive the changed value as an argument. It reads the current value from the notifier. This is why a view should treat the view model as the source of truth.
Connecting a widget
ListenableBuilder manages the listener registration for you. It listens while the widget is mounted and rebuilds its builder when the notifier calls notifyListeners().
ListenableBuilder(
listenable: viewModel,
builder: (context, child) {
return Text('Count: ${viewModel.count}');
},
)The builder can run for reasons besides a notification, such as an ordinary widget rebuild. Always read the current state inside the builder instead of caching a value from an earlier build.
Provider offers the same basic connection through Consumer<T>. The choice between ListenableBuilder and Provider is mainly about how you locate and provide the view model. Both depend on ChangeNotifier notifications.
What ChangeNotifier does not do
ChangeNotifier does not:
- detect mutations automatically
- compare state before notifying
- run asynchronous work
- prevent business logic from entering widgets
- guarantee that a notification means every field changed
Call notifyListeners() after every state transition that the UI must observe. Calling it too often can cause unnecessary rebuilds. Failing to call it leaves the UI displaying stale state.
Disposal and common mistakes
A notifier should stop notifying after its owner disposes it. Flutter calls dispose when a widget-owned view model is removed. Do not call notifyListeners() after disposal. An unfinished asynchronous operation can cause this mistake:
Future<void> load() async {
final result = await repository.fetch();
_items = result;
if (!hasListeners) return;
notifyListeners();
}hasListeners only tells you whether callbacks are registered. It is not a complete lifecycle guarantee. A stronger design adds a private disposed flag, cancels work where possible, or checks mounted when using a framework object that provides it. Ensure the object that creates the view model also owns and disposes it.
Exercise
Why must a view model update its fields before calling notifyListeners()?
Show answer
Listeners rebuild synchronously and read the view model immediately. Updating first ensures they see one consistent, current state instead of stale values.