listen<T> method

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

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

@override
void listen<T>(
  ProviderListenable<T> provider,
  void Function(T? previous, T value) listener, {
  void Function(Object error, StackTrace stackTrace)? onError,
}) {
  _assertNotDisposed();
  assert(
    debugDoingBuild,
    'ref.listen can only be used within the build method of a ConsumerWidget',
  );

  // We can't implement a fireImmediately flag because we wouldn't know
  // which listen call was preserved between widget rebuild, and we wouldn't
  // want to call the listener on every rebuild.
  final sub = _container.listen<T>(provider, listener, onError: onError);
  _listeners.add(sub);
}