Sub topic 11
Reacting to changes with ref.listen
ref.watch rebuilds a widget when a provider changes. Some changes should not rebuild anything. Showing a snackbar, navigating to another screen, logging an event, or resetting a related piece of state are side effects, and ref.listen is the tool for them. This chapter covers how it works, how it differs from ref.watch, and the mistakes that come up in practice.
It assumes you know ref.watch versus ref.read, Notifier, and AsyncValue from earlier chapters.
Why watching is the wrong tool for side effects
build can run many times per second and must have no side effects. If you call showSnackBar or Navigator.push from build because a watched value looks a certain way, the action repeats on every rebuild. Flutter also throws an error when you try to show a snackbar or push a route while the widget tree is being built.
ref.listen solves this by separating the two jobs:
ref.watchdescribes what the UI looks like for the current state.ref.listenruns a callback once for each change, with the old and new value.
The basic form
ref.listen<T>(provider, (previous, next) {
// react to the change
});The callback receives previous and next. The callback runs when the provider's value changes. The previous argument is null the first time the callback runs in some cases (for example, when the provider is first created while you are listening), so always treat it as nullable.
Here is a complete example using the counter from the Notifier chapter. It shows a snackbar when the count reaches 5.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<int>(counterProvider, (previous, next) {
if (next == 5) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('You reached 5')),
);
}
});
final count = ref.watch(counterProvider);
return Scaffold(
body: Center(child: Text('$count')),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}The widget still watches the counter to render the number. The listener adds a separate, one-time reaction. Calling ref.listen inside build is correct. Riverpod keeps one subscription per call site and closes it when the widget is disposed. It also replaces the callback on each rebuild, so the closure always sees the current context.
How the notification flows
The callback runs as part of the state change. The rebuild happens later, on the next frame. A listener is not tied to the widget's build output, so a widget can listen to a provider without watching it.
Reacting to errors in AsyncValue
The most common use is surfacing a failed load or save. In an AsyncNotifier, an exception leaves the provider in AsyncError, and you can pick that up in a listener.
class TodoListener extends ConsumerWidget {
const TodoListener({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<AsyncValue<List<Todo>>>(todoListProvider, (previous, next) {
if (next.hasError && !next.isLoading) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not load todos')),
);
}
});
return child;
}
}The !next.isLoading check matters. When you refresh a provider that already holds an error, the new AsyncValue can be loading and still carry the old error. Without the check you would show the snackbar again the moment the retry begins.
You can also compare with previous to react only to a transition:
ref.listen<AsyncValue<List<Todo>>>(todoListProvider, (previous, next) {
final wasLoaded = previous?.hasValue ?? false;
if (wasLoaded && next.hasError) {
// The list was showing, and a refresh just failed.
}
});Listening to part of a value with select
A listener fires on every change to the provider's value. To react to one field, combine listen with select, as you did with watch:
ref.listen<int>(
profileProvider.select((p) => p.age),
(previous, next) {
if (previous != null && next > previous) {
debugPrint('Happy birthday, now $next');
}
},
);The callback runs only when age changes, not when name changes.
Listening outside build: listenManual
ref.listen belongs in build. In a ConsumerStatefulWidget, use ref.listenManual to subscribe once from initState or from an event handler. It returns a ProviderSubscription, and it also accepts fireImmediately: true, which calls the callback right away with the current value.
class AnalyticsPage extends ConsumerStatefulWidget {
const AnalyticsPage({super.key});
@override
ConsumerState<AnalyticsPage> createState() => _AnalyticsPageState();
}
class _AnalyticsPageState extends ConsumerState<AnalyticsPage> {
late final ProviderSubscription<int> _subscription;
@override
void initState() {
super.initState();
_subscription = ref.listenManual<int>(
counterProvider,
(previous, next) => debugPrint('Counter: $previous -> $next'),
fireImmediately: true,
);
}
@override
void dispose() {
_subscription.close();
super.dispose();
}
@override
Widget build(BuildContext context) => const Placeholder();
}Subscriptions made with listenManual in a ConsumerState are closed automatically on dispose. Calling close() yourself is still the right move if you want to stop listening earlier.
Listening inside providers
ref.listen also exists on the ref inside a provider or Notifier. Use it to keep one piece of state in sync with another. This example resets the page number whenever the search text changes:
class SearchQuery extends Notifier<String> {
@override
String build() => '';
void set(String value) => state = value;
}
final searchQueryProvider =
NotifierProvider<SearchQuery, String>(SearchQuery.new);
class PageIndex extends Notifier<int> {
@override
int build() {
ref.listen<String>(searchQueryProvider, (_, __) => state = 0);
return 0;
}
void next() => state++;
}
final pageIndexProvider = NotifierProvider<PageIndex, int>(PageIndex.new);The difference from ref.watch(searchQueryProvider) in build is important. A watch would rebuild PageIndex and rerun build, which discards its state and also resets it to 0, but it would do so for any reason the dependency changes. A listen leaves the notifier alive and changes only what you tell it to. Choose watch when the provider's value is a function of the other provider. Choose listen when you want to run an action.
Behavior to remember
| Behavior | Detail |
|---|---|
| Initial value | The callback does not run for the first value unless you use `listenManual` with `fireImmediately: true`. |
| Equal values | Notifiers skip notifying when the new state is equal to the old state, so the callback does not run. |
| Keeping state alive | A listener counts as a listener, so it keeps an `autoDispose` provider alive while it is subscribed. |
| Error handling | Pass `onError` to handle a provider that throws, without it the error goes to the zone's error handler. |
| Where to call it | `ref.listen` in `build` for widgets, `ref.listenManual` elsewhere, never inside callbacks such as `onPressed`. |
Common mistakes
- Using the callback to update widget state. If the result is something the UI displays, derive it with
ref.watch. Reservelistenfor actions. - Using a stale
context. After anawaitinside a callback, checkcontext.mountedbefore using the context. - Showing the same error repeatedly. Compare with
previous, or checkisLoading, so one failure produces one message. - Listening in a widget that is not on screen. A listener runs only while its widget is in the tree. If the user may have left the page, place the listener high enough, for example on a widget wrapping the whole
Scaffold, asTodoListenerdoes with itschild.
Exercise
A ConsumerWidget shows a saved confirmation snackbar by calling ScaffoldMessenger.of(context).showSnackBar(...) inside build whenever ref.watch(saveProvider).hasValue is true. The snackbar appears many times and sometimes triggers a framework error. What should you change, and which ref method fits?
Show answer
Move the snackbar call out of build into a ref.listen<AsyncValue<void>>(saveProvider, (previous, next) { ... }) call placed at the top of build. Inside the callback, show the snackbar only on the transition to success, for example when previous?.isLoading == true && next.hasValue && !next.isLoading. Keep ref.watch only for values that decide what the widget draws.