addListener method

  1. @override
void addListener(
  1. Function listener, [
  2. Iterable<T>? properties
])
override

Registers listener for the given properties. listener must not be null. If properties is null or empty, listener will be added as a global listener, meaning it will be invoked for all property changes. This is the default behavior of ChangeNotifier. listener must either accept no parameters or a single T parameter. If listener accepts a T parameter, it will be invoked with the property name provided by notifyListeners. The same listener can be added for multiple properties. Adding the same listener for the same property is a no-op. Adding a listener for a non-existent property will not fail, but is functionally pointless.

Implementation

@override
void addListener(Function listener, [Iterable<T>? properties]) {
  assert(_debugAssertNotDisposed());
  assert(listener is VoidCallback || listener is PropertyCallback<T>, 'Listener must be a Function() or Function(T?)');

  // Register global listener only
  if (properties == null || properties.isEmpty) {
    _addListener(_globalListeners!, listener);
    return;
  }

  // Register listener for every property
  for (final property in properties) {
    if (!_propertyListeners!.containsKey(property)) {
      _propertyListeners![property] = ObserverList<Function>();
    }
    _addListener(_propertyListeners![property]!, listener);
  }
}