Commit b00efda7 authored by Adam Barth's avatar Adam Barth Committed by GitHub

Improve change notifier (#4747)

This patch improves some subtle behaviors about the change notifier.
parent 490622b4
...@@ -30,23 +30,26 @@ abstract class ChangeNotifier { ...@@ -30,23 +30,26 @@ abstract class ChangeNotifier {
/// This method should only be called by the object's owner. /// This method should only be called by the object's owner.
@mustCallSuper @mustCallSuper
void dispose() { void dispose() {
_listeners = null; _listeners = const <VoidCallback>[];
} }
/// Call all the registered listeners. /// Call all the registered listeners.
/// ///
/// Call this method whenever the object changes, to notify any clients the /// Call this method whenever the object changes, to notify any clients the
/// object may have. /// object may have. Listeners that are added during this iteration will not
/// be visited. Listeners that are removed during this iteration will not be
/// visited after they are removed.
/// ///
/// Exceptions thrown by listeners will be caught and reported using /// Exceptions thrown by listeners will be caught and reported using
/// [FlutterError.reportError]. /// [FlutterError.reportError].
@protected @protected
void notifyListeners() { void notifyListeners() {
if (_listeners != null) { if (_listeners != null) {
List<VoidCallback> listeners = new List<VoidCallback>.from(_listeners); List<VoidCallback> localListeners = new List<VoidCallback>.from(_listeners);
for (VoidCallback listener in listeners) { for (VoidCallback listener in localListeners) {
try { try {
listener(); if (_listeners.contains(listener))
listener();
} catch (exception, stack) { } catch (exception, stack) {
FlutterError.reportError(new FlutterErrorDetails( FlutterError.reportError(new FlutterErrorDetails(
exception: exception, exception: exception,
......
...@@ -102,7 +102,7 @@ void main() { ...@@ -102,7 +102,7 @@ void main() {
test.addListener(listener2); test.addListener(listener2);
test.addListener(listener3); test.addListener(listener3);
test.notify(); test.notify();
expect(log, equals(<String>['listener1', 'listener2', 'listener3'])); expect(log, equals(<String>['listener1', 'listener2']));
log.clear(); log.clear();
test.notify(); test.notify();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment