Sub topic 3
How ChangeNotifier notifies listeners
This chapter explains the mechanism that every later chapter relies on: how a ChangeNotifier tells widgets that its state changed. It assumes you know basic Dart (classes, async/await, Futures), the difference between StatelessWidget and StatefulWidget, and why setState gets hard to manage in larger widgets.
The Listenable contract
Flutter defines a small interface called Listenable. It has two methods:
addListener(VoidCallback listener)registers a function to call later.removeListener(VoidCallback listener)unregisters it.
A Listenable makes no promise about what changed. It only says "something changed, come look." Listeners then read the current state themselves.
ChangeNotifier is the standard implementation of Listenable. It stores a list of listeners and adds one method, notifyListeners(), which calls every registered listener. You subclass it, keep your state in private fields, and call notifyListeners() after you change them.
import 'package:flutter/foundation.dart';
class Counter extends ChangeNotifier {
int _value = 0;
int get value => _value;
void increment() {
_value++;
notifyListeners();
}
}
void main() {
final counter = Counter();
void onChange() => print('value is now ${counter.value}');
counter.addListener(onChange);
counter.increment(); // prints: value is now 1
counter.increment(); // prints: value is now 2
counter.removeListener(onChange);
counter.increment(); // prints nothing
counter.dispose();
}This runs as plain Dart with the Flutter SDK available. No widgets are involved. That is the reason view models built on ChangeNotifier are easy to test.
What notifyListeners does
Calling notifyListeners() runs each listener synchronously, in the order they were added, before the call returns. Three details matter in practice.
- There is no change detection.
notifyListeners()does not compare old and new values. If you call it without changing anything, listeners still run. If you change a field and forget to call it, nothing happens and the screen goes stale. - There is no batching. Each call notifies immediately. Three calls in a row produce three rounds of listener calls.
- Listeners should be cheap. A listener typically calls
setStateor marks a widget dirty. Flutter then coalesces the actual rebuild into the next frame, so several notifications within one frame produce one rebuild.
The following diagram shows the full path from a user tap to a repainted screen.
Notice the last step. The widget reads the new state through getters. The notification carries no data.
Mutating state: the order of operations
Change the state first, then notify. A listener that runs during notifyListeners() reads whatever the fields hold at that moment, so notifying before the change shows the old value.
import 'package:flutter/foundation.dart';
class Wrong extends ChangeNotifier {
int _value = 0;
int get value => _value;
void increment() {
notifyListeners(); // listeners see the old value
_value++;
}
}In this class a widget would rebuild with the stale number, and nothing would trigger a second rebuild.
For methods with several steps, notify once at the end of a group of changes rather than after every field:
import 'package:flutter/foundation.dart';
class Profile extends ChangeNotifier {
String _first = '';
String _last = '';
String get fullName => '$_first $_last'.trim();
void rename(String first, String last) {
_first = first;
_last = last;
notifyListeners(); // one notification for both fields
}
}If you notified after each assignment, a listener could observe a half-updated name such as the new first name with the old last name.
Asynchronous methods notify more than once
Methods that await something usually notify at least twice: once when work starts, once when it finishes. The view model from the topic's later chapters does exactly this.
import 'package:flutter/foundation.dart';
class Loader extends ChangeNotifier {
bool _isLoading = false;
String? _data;
bool get isLoading => _isLoading;
String? get data => _data;
Future<void> load() async {
_isLoading = true;
notifyListeners(); // 1: show a spinner
await Future<void>.delayed(const Duration(milliseconds: 200));
_data = 'loaded';
_isLoading = false;
notifyListeners(); // 2: show the result
}
}Between the two notifications, control returns to the event loop, so the UI can draw the spinner. Without the first call, the user would see a frozen screen for 200 ms.
Listener management and disposal
A ChangeNotifier holds strong references to its listeners. If a widget registers a listener and never removes it, the notifier keeps that widget's state object alive and keeps calling into it.
dispose() is the end of a notifier's life. After you call it:
- The listener list is released.
- Calling
addListenerornotifyListenersthrows aFlutterErrorin debug mode, with the message that the notifier was used after being disposed.
That second point is the origin of a classic bug. An async method awaits a network call, the screen closes and the view model is disposed, then the call finishes and the method calls notifyListeners(). The result is an exception. The fix is a guard:
import 'package:flutter/foundation.dart';
class SafeLoader extends ChangeNotifier {
bool _disposed = false;
String? _data;
String? get data => _data;
Future<void> load() async {
final result = await Future.value('loaded');
_data = result;
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}Later chapters on lifecycle show how ChangeNotifierProvider and StatefulWidget.dispose decide who owns and disposes the view model. For now, remember the rule: whoever creates a notifier disposes it.
Adding and removing listeners by hand
Widgets such as ListenableBuilder do the registration for you, and you will use them for most views. Writing the same thing by hand shows what they do:
import 'package:flutter/material.dart';
class CounterText extends StatefulWidget {
const CounterText({super.key, required this.listenable});
final Listenable listenable;
@override
State<CounterText> createState() => _CounterTextState();
}
class _CounterTextState extends State<CounterText> {
@override
void initState() {
super.initState();
widget.listenable.addListener(_onChanged);
}
@override
void didUpdateWidget(CounterText oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.listenable != widget.listenable) {
oldWidget.listenable.removeListener(_onChanged);
widget.listenable.addListener(_onChanged);
}
}
@override
void dispose() {
widget.listenable.removeListener(_onChanged);
super.dispose();
}
void _onChanged() => setState(() {});
@override
Widget build(BuildContext context) => const Text('changed');
}Two edge cases appear here. First, if the parent passes a different notifier, you must move the listener (didUpdateWidget). Second, the widget must remove its listener in dispose, or the notifier will call setState on a dead state object. ListenableBuilder handles both cases.
Edge cases to know
- Removing a listener during notification. It is safe. The notifier tolerates listeners that remove themselves while it iterates.
- Exceptions in a listener. An exception from one listener is reported through Flutter's error handling, and the remaining listeners still run.
- Notifying from inside
build. CallingnotifyListeners()while the framework is building widgets can trigger a "setState called during build" error in listening widgets. Start work frominitStateor an event handler, not frombuild. hasListeners. This getter tells you whether anyone is registered. It is rarely needed in a view model, but it is useful for deciding whether to start or stop a background subscription.- Mutable collections. If you expose a
Listand mutate it in place, listeners rebuild, but a widget that compares old and new lists by identity can miss the change. Prefer replacing the list with a new one, which fits the immutable models in later chapters.
| Situation | Result |
|---|---|
| `notifyListeners()` with no state change | Listeners run anyway |
| State change without `notifyListeners()` | UI stays stale |
| Several notifications in one frame | Listeners run each time, rebuild happens once |
| `notifyListeners()` after `dispose()` | Throws `FlutterError` in debug mode |
| Listener not removed | Notifier keeps the listener alive and calls it |
Exercise
A view model method sets _isLoading = true, awaits a repository call, then sets _isLoading = false, and calls notifyListeners() only once at the very end. What does the user see, and what is the fix?
Show answer
The user never sees the loading state, because the view never receives a notification when _isLoading becomes true. The screen stays as it was until the call finishes. The fix is to call notifyListeners() right after setting _isLoading = true, before the await, and again after the work finishes.
Exercise
A screen is closed while load() is awaiting the network, and the debug console shows a FlutterError about using a ChangeNotifier after it was disposed. Which line causes it, and how can you prevent it?
Show answer
The notifyListeners() call that runs after the await completes, because the owner already called dispose(). Prevent it by tracking a _disposed flag set in an overridden dispose() (calling super.dispose()), and skipping notifyListeners() when the flag is true.