listen<T> abstract method

void listen<T>(
  1. ProviderListenable<T> provider,
  2. void listener(
    1. T? previous,
    2. T next
    ),
  3. {void onError(
    1. Object error,
    2. StackTrace stackTrace
    )?}
)

Listen to a provider and call listener whenever its value changes, without having to take care of removing the listener.

The listen method should exclusively be used within the build method of a widget:

Consumer(
  builder: (context, ref, child) {
    ref.listen<int>(counterProvider, (prev, next) {
      print('counter changed $next');
    });
  },
)

When used inside build, listeners will automatically be removed if a widget rebuilds and stops listening to a provider.

For listening to a provider from outside build, consider using listenManual instead.

This is useful for showing modals or other imperative logic.

Implementation

void listen<T>(
  ProviderListenable<T> provider,
  void Function(T? previous, T next) listener, {
  void Function(Object error, StackTrace stackTrace)? onError,
});