addListener method

RemoveListener addListener(
  1. Listener<Configuration> listener, {
  2. bool fireImmediately = true,
})
inherited

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

RemoveListener addListener(
  Listener<T> listener, {
  bool fireImmediately = true,
}) {
  assert(() {
    if (!_debugCanAddListeners) {
      throw ConcurrentModificationError();
    }
    return true;
  }(), '');
  assert(_debugIsMounted(), '');
  final listenerEntry = _ListenerEntry(listener);
  _listeners.add(listenerEntry);
  try {
    assert(_debugSetCanAddListeners(false), '');
    if (fireImmediately) {
      listener(state);
    }
  } catch (err, stack) {
    listenerEntry.unlink();
    onError?.call(err, stack);
    rethrow;
  } finally {
    assert(_debugSetCanAddListeners(true), '');
  }

  return () {
    if (listenerEntry.list != null) {
      listenerEntry.unlink();
    }
  };
}