Sub topic 5
ref.watch versus ref.read
This chapter assumes you can write a ConsumerWidget, declare a Provider and a NotifierProvider, and know that ProviderScope sits at the root of the app. The earlier chapters in this tutorial cover those. The chapter explains how ref.watch and ref.read differ, when each is correct, and which errors come from mixing them up.
The working model
Both methods return the current value of a provider. They differ in what happens afterwards.
ref.watchreturns the value and also subscribes the caller to the provider. When the provider's value changes, Riverpod re-runs the caller. For a widget, the caller is itsbuildmethod. For a provider, it is the provider's creation function.ref.readreturns the value once and creates no subscription. If the value changes later, the caller is not told.
Use watch when the result you produce should always match the current value. Use read when you need the value at one moment, such as when the user taps a button.
Using ref.watch
Call ref.watch while building something that depends on state. The widget below displays the counter, so it must rebuild whenever the count changes.
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);
void main() {
runApp(const ProviderScope(child: MaterialApp(home: CounterPage())));
}
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
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 same page uses both methods. ref.watch(counterProvider) runs inside build, so the Text stays current. ref.read(counterProvider.notifier) runs inside onPressed, a callback that fires only on a tap.
ref.watch also works inside a provider's body. A provider that watches another one is recomputed whenever the watched value changes:
final isEvenProvider = Provider<bool>((ref) {
return ref.watch(counterProvider).isEven;
});Using ref.read
Call ref.read when you need a value or an object at a single point in time and nothing should rebuild because of it. Typical places are:
- Event callbacks such as
onPressed,onChangedandonSubmitted. - Methods on a
Notifier, where you read other providers to make a decision. - One-off actions such as
initStatein aConsumerStatefulWidget.
The Notifier below reads a limit provider when add is called. It has no reason to re-run when the limit changes, because the check happens only at the moment of adding.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final maxItemsProvider = Provider<int>((ref) => 3);
class Cart extends Notifier<List<String>> {
@override
List<String> build() => const [];
void add(String item) {
final max = ref.read(maxItemsProvider);
if (state.length >= max) return;
state = [...state, item];
}
}
final cartProvider = NotifierProvider<Cart, List<String>>(Cart.new);Why the .notifier read is safe in a callback
counterProvider.notifier returns the Notifier object itself, not its state. That object is created once and stays the same while the provider is alive. You only need it to call methods, so reading it once is enough.
The decision rule
Ask where the code runs. Only the first row of the table calls for watch. Anything that runs later, in response to an event, calls for read.
| Where the code runs | Use | Reason |
|---|---|---|
| `build` of a `ConsumerWidget` | `ref.watch` | The UI must follow the state. |
| Body of a provider | `ref.watch` | The derived value must follow its inputs. |
| `Notifier.build` | `ref.watch` | The initial state should rebuild when inputs change. |
| Button or gesture callback | `ref.read` | The value is needed once, at event time. |
| Method on a `Notifier` | `ref.read` | The method runs on demand, not reactively. |
| Side effect such as a snackbar | `ref.listen` | You react to a change without rebuilding the UI. |
Common errors
Using ref.read in build
Replacing watch with read in build is the most frequent mistake. The screen draws the first value correctly, and after that it never updates.
// Bug: the Text shows 0 forever, even after increments.
final count = ref.read(counterProvider);Nothing is broken at runtime, so no exception tells you. The symptom is a UI that is stuck. Fix it by using ref.watch.
Using ref.read inside a provider
The same bug appears in providers, where it is harder to spot:
final staleDoubleProvider = Provider<int>((ref) {
return ref.read(counterProvider) * 2; // computed once, then cached
});
final doubleProvider = Provider<int>((ref) {
return ref.watch(counterProvider) * 2; // recomputed on every change
});A provider caches its result. With read, nothing tells Riverpod to invalidate that cache, so the value stays at whatever it was on first use. In staleDoubleProvider, it stays at 0.
Using ref.watch in a callback
Calling ref.watch inside onPressed is the opposite error. A widget's ref.watch is meant for the build phase, and debug builds raise an assertion error when it is called elsewhere. Even where it does not throw, a subscription created in a callback has no clear moment at which Riverpod can clean it up. Use ref.read there.
Watching in Notifier methods
Inside a Notifier method, ref.watch is the wrong tool for the same reason. Use ref.read to get what you need, as Cart.add does above. Reserve ref.watch for build.
Watching the notifier and expecting rebuilds
ref.watch(counterProvider.notifier) is valid, but it only subscribes you to the notifier object. That object does not change when the state changes, so the widget will not rebuild on increments. Watch counterProvider to display the value. Use .notifier only to call methods.
Reading when you want to react
If you want to show a snackbar every time a value becomes an error, neither method fits. watch would rebuild the widget just to run a side effect, and read would miss the change. Use ref.listen, which is covered in its own chapter.
A practical habit
Write ref.watch in build for values that appear on screen. Write ref.read(...notifier) in callbacks for actions. If you catch yourself writing ref.read at the top of a build method to fetch a value, change it to ref.watch. Riverpod's lint package (riverpod_lint) also reports some misuse of ref and can catch these mistakes before you run the app.
Exercise
A Provider is declared as final totalProvider = Provider<int>((ref) => ref.read(cartProvider).length);. The cart screen shows the total, but it stays at 0 after items are added. What is wrong, and what is the fix?
Show answer
The provider body uses ref.read, so it computes length once and caches the result. Nothing tells Riverpod to recompute it when the cart changes. Change it to ref.watch(cartProvider).length so the provider is recomputed whenever the cart state changes, and widgets that watch totalProvider rebuild with the new value.
Exercise
In a ConsumerWidget, where should you call ref.read(cartProvider.notifier).add('Apple'), and why not call ref.watch(cartProvider.notifier) there?
Show answer
Call it inside an event callback such as onPressed. It runs once when the user acts and needs no subscription. ref.watch belongs in build, and watching .notifier would never trigger a rebuild on state changes anyway, because the notifier object stays the same.