watch<Notifier> method

  1. @override
Notifier watch<Notifier>(
  1. ListeneableProvider<Notifier> providerOrTarget
)
override

read a Notifier from one provider and subscribe the widget to the changes of this Notifier.

providerOrTarget this param is required to decide when the Consumer needs to be rebuilded, if providerOrTarget is a SimpleProvider or a StateProvider the widget will be rebuilded when the notify method is called inside a SimpleNotifier or StateNotifier.

If providerOrTarget is a value gotten from .select, .ids or .when the widget only will be rebuilded depending of the condition of each method.

Implementation

@override
Notifier watch<Notifier>(ListeneableProvider<Notifier> providerOrTarget) {
  // if the widget was rebuilded
  if (_isExternalBuild) {
    _clearDependencies();
  }
  _isExternalBuild = false;
  final target =
      providerOrTarget is Target ? providerOrTarget as Target : null;

  late Notifier notifier;

  if (target != null) {
    // If [providerOrTarget] is a value gotten from .select, .ids or .when
    notifier = target.notifier as Notifier;
  } else {
    // if [providerOrTarget] is a [SimpleProvider] or a [StateProvider]
    notifier = (providerOrTarget as BaseProvider<Notifier>).read;
  }

  final insideDependencies = _dependencies.containsKey(notifier);

  // if there is not a listener for the current provider
  if (!insideDependencies) {
    late void Function(dynamic) listener;
    // if the data passed to the watch function
    // was gotten using the .ids, .select or .when methods
    if (target != null) {
      target.rebuild = _rebuild;
      if (notifier is StateNotifier) {
        if (target.filter == Filter.select) {
          createStateSelectListener(target);
        } else {
          createWhenListener(target);
        }
      } else {
        createSimpleSelectListener(target);
      }
      listener = target.listener;
    } else {
      listener = (_) => _rebuild();
    }
    // add the listener to the current notifier
    _dependencies[notifier as BaseNotifier] = listener;
    (notifier as ListeneableNotifier).addListener(listener);
  }
  return notifier; // coverage:ignore-line
}