listen<State> method

ProviderSubscription<State> listen<State>(
  1. ProviderListenable<State> provider,
  2. void listener(
    1. State? previous,
    2. State next
    ), {
  3. bool fireImmediately = false,
  4. bool weak = false,
  5. void onError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
})

Listen to a provider and call listener whenever its value changes.

Listeners will automatically be removed when the provider rebuilds (such as when a provider listened with Ref.watch changes).

Returns an object that allows cancelling the subscription early.

fireImmediately (false by default) can be optionally passed to tell Riverpod to immediately call the listener with the current value.

onError can be specified to listen to uncaught errors in the provider.
Note:
onError will not be triggered if the provider catches the exception and emit a valid value out of it. As such, if a FutureProvider/StreamProvider fail, onError will not be called. Instead the listener will receive an AsyncError.

  • weak (false by default) can be optionally passed to have the listener not cause the provider to be initialized and kept alive. This enables listening to changes on a provider, without causing it to perform any work if it currently isn't used.

Implementation

ProviderSubscription<State> listen<State>(
  ProviderListenable<State> provider,
  void Function(State? previous, State next) listener, {
  bool fireImmediately = false,
  bool weak = false,
  void Function(Object error, StackTrace stackTrace)? onError,
}) {
  assert(
    !(weak && fireImmediately),
    'Cannot specify both weak and fireImmediately',
  );

  final sub = provider._addListener(
    this,
    listener,
    weak: weak,
    onError: onError ?? defaultOnError,
    onDependencyMayHaveChanged: null,
  );
  _handleFireImmediately(
    container,
    sub,
    fireImmediately: fireImmediately,
  );

  sub.impl._listenedElement.addDependentSubscription(sub.impl);

  return sub;
}