addListener method

  1. @override
RemoveListener addListener(
  1. void listener(
    1. T
    ), {
  2. bool fireImmediately = true,
})
override

Subscribes to this object.

The listener callback will be called immediately on addition and synchronously whenever state changes. Set fireImmediately to false if you want to skip the first, immediate execution of the listener.

To remove this listener, call the function returned by addListener:

StateNotifier<Model> example;
final removeListener = example.addListener((value) => ...);
removeListener();

Listeners cannot add other listeners.

Adding and removing listeners has a constant time-complexity.

Implementation

@override
RemoveListener addListener(void Function(T) listener,
    {bool fireImmediately = true}) {
  final _listener = (T? value) {
    // if `value` is `null` and `T` is actually a nullable
    // type, then the listener MUST be called with `null`
    if (_typesEqual<T, T?>() && value == null) {
      listener(null as T);
    } else {
      // if `value != null` and `T` is non-nullable, also
      listener(value!);
    }
  };
  return super.addListener(_listener, fireImmediately: false);
}