Sub topic 11
Reacting to changes with `ref.listen`
This chapter assumes Dart classes, generics, Future, and async/await. You should also know Flutter’s build method and the difference between rebuilding a widget and running an event callback.
What `ref.listen` does
ref.listen watches a provider and calls a function when the provider’s value changes. The callback receives both the previous value and the new value.
Use it for a side effect. A side effect is an action that happens because of a state change but does not describe the widget’s layout. Showing a snackbar, navigating to another page, and logging an event are side effects.
| Riverpod operation | Main purpose | Rebuilds the widget? |
|---|---|---|
| `ref.watch` | Read state used by the UI | Yes |
| `ref.read` | Read state in an event callback | No |
| `ref.listen` | React to a state change | No |
A listener belongs in a ConsumerWidget, Consumer, or another widget that receives a WidgetRef. Riverpod removes the listener when that widget is disposed.
Listening to asynchronous state
An asynchronous provider exposes an AsyncValue. AsyncValue represents loading, data, or error. The listener can inspect the new value and respond only to the transition it needs.
The following example shows a snackbar after the list loads and another snackbar if loading fails:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Todo {
const Todo(this.title);
final String title;
}
final todoProvider = FutureProvider<List<Todo>>((ref) async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return const [Todo('Read the Riverpod docs'), Todo('Write a test')];
});
class TodoPage extends ConsumerWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<AsyncValue<List<Todo>>>(todoProvider, (previous, next) {
if (next.hasValue && previous?.isLoading == true) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Todos loaded')),
);
}
if (next.hasError && !next.isLoading) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not load todos')),
);
}
});
final todos = ref.watch(todoProvider);
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: todos.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(
child: Text('Loading failed: $error'),
),
data: (items) => ListView(
children: [
for (final todo in items) ListTile(title: Text(todo.title)),
],
),
),
);
}
}
void main() {
runApp(
const ProviderScope(
child: MaterialApp(home: TodoPage()),
),
);
}The widget uses ref.watch(todoProvider) because the visible list must rebuild when the provider changes. It uses ref.listen separately because a snackbar should not be part of the widget tree.
Common mistakes
Do not use ref.listen to calculate values needed by the UI. Use a derived provider for that. A listener is also a poor place to mutate the provider it listens to. That can create repeated updates or a loop.
A listener may run more than once during refreshes. Check previous and next when the effect should happen only for a particular transition. Keep listeners near the widget that owns the effect, so a page does not show duplicate notifications after several widgets are mounted.
Exercise
Why does the example use both ref.watch and ref.listen for the same provider?
Show answer
ref.watch rebuilds the page so it can display loading, error, or data. ref.listen runs a snackbar side effect without rebuilding the page for that purpose.