listen<StateT> abstract method

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

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 at the root of the build:

Good: Use listen inside the build method.

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Correct, we are inside the build method and at its root.
    ref.listen(counterProvider, (prev, next) {});
  }
}

Bad: Do not use listen inside builders.

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ListView.builder(
      itemBuilder: (context) {
         // This is accepted, as we are at the root of a "builder"
         ref.listen(counterProvider, (prev, next) {});
      },
    );
  }
}

Bad: Don't use listen outside of the build method.

class Example extends ConsumerStatefulWidget {
  @override
  ExampleState createState() => ExampleState();
}

class ExampleState extends ConsumerState<Example> {
  @override
  void initState() {
    super.initState();
    // Incorrect, we are not inside the build method.
    ref.listen(counterProvider, (prev, next) {});
  }
}

Bad: Don't use listen inside event handles withing build method.

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ElevatedButton(
      onTap: () {
        // Incorrect, we are inside the build method, but neither at its
        // root, nor inside a "builder".
        ref.listen(counterProvider, (prev, next) {});
      }
    );
  }
}

Note: Listeners will automatically be removed if a widget rebuilds and stops listening to a provider.

See also:

  • listenManual, for listening to a provider from outside build.
  • watch, to listen to providers in a declarative manner.
  • read, to read a provider without listening to it.

This is useful for showing modals or other imperative logic.

Implementation

@override
void listen<StateT>(
  ProviderListenable<StateT> provider,
  void Function(StateT? previous, StateT next) listener, {
  void Function(Object error, StackTrace stackTrace)? onError,
  bool weak = false,
});