Sub topic 4
Reading other providers with ref
Providers rarely stand alone. A cart total needs the cart and a tax rate. A checkout action needs the total and an API client. This chapter covers the three ways a generated provider reads another one: ref.watch, ref.read and ref.listen. It also covers when each is correct and what goes wrong when you pick the wrong one.
You should already know how to run build_runner (covered in the setup chapter), how @riverpod turns a function or class into a provider, and how ConsumerWidget and ref.watch work in the widget tree.
Where ref comes from
Every provider gets a Ref object. Where it appears depends on the provider's shape:
- In a functional provider,
refis the first parameter of the annotated function. - In a class-based provider,
refis a property of the notifier. It is available insidebuildand inside every method. - In a widget,
refis aWidgetRef, passed tobuildbyConsumerWidgetorConsumerState.
Ref and WidgetRef share the same three methods. The rules for when to call them differ slightly, and that is where most mistakes happen.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'cart.g.dart';
@riverpod
int taxPercent(Ref ref) => 20;
@riverpod
class Cart extends _$Cart {
@override
List<int> build() => [];
void add(int priceCents) => state = [...state, priceCents];
}
@riverpod
int cartTotal(Ref ref) {
final items = ref.watch(cartProvider);
final tax = ref.watch(taxPercentProvider);
final subtotal = items.fold<int>(0, (sum, price) => sum + price);
return subtotal + subtotal * tax ~/ 100;
}The generator creates taxPercentProvider, cartProvider and cartTotalProvider in cart.g.dart. You pass those generated objects to ref. With generator 2.x, the parameter type is the generated CartTotalRef instead of Ref. The calls inside the body are identical.
ref.watch: declare a dependency
ref.watch(provider) returns the provider's current value. It also records that the calling provider depends on it. When the watched provider changes, Riverpod discards the calling provider's state and runs its body again.
In the example above, cartTotal watches cartProvider and taxPercentProvider. Calling add(500) on the cart updates the cart state. Riverpod then marks cartTotal as stale and recomputes it the next time something reads it. Nothing in cartTotal subscribes or unsubscribes by hand. The dependency graph is built from the ref.watch calls that run.
Arrows show the direction of change. When cartProvider changes, cartTotalProvider rebuilds, and then CartSummary rebuilds because it watches the total.
Watching async providers
If the watched provider returns a Future, ref.watch gives you an AsyncValue, not the data. You can handle the states yourself, or you can wait for the data by watching .future:
@riverpod
Future<String> userName(Ref ref) async => 'Ada';
@riverpod
Future<String> welcomeMessage(Ref ref) async {
final name = await ref.watch(userNameProvider.future);
return 'Welcome back, $name';
}ref.watch(userNameProvider.future) returns a Future<String>. The await suspends welcomeMessage until userName completes. If userName fails, the error propagates and welcomeMessage fails too. Watching .future keeps welcomeMessage subscribed. If userName later emits a new value, welcomeMessage runs again.
Narrowing with select
Watching a whole object rebuilds the caller on any change to it. If you only need one field, use select:
@riverpod
bool hasItems(Ref ref) {
return ref.watch(cartProvider.select((items) => items.isNotEmpty));
}hasItems now recomputes only when the result of isNotEmpty changes, not on every add call after the first. The same works in widgets: ref.watch(cartProvider.select((items) => items.length)).
Watching a notifier
To get the notifier object itself, watch .notifier:
final cart = ref.watch(cartProvider.notifier);This returns the same Cart instance for the life of the provider. It does not trigger rebuilds when the state changes. That is why ref.read(cartProvider.notifier) is the usual choice in callbacks (see the next section).
ref.read: a one-time read
ref.read(provider) returns the current value and does nothing else. It creates no dependency, so the caller does not rebuild when the value changes. Use it when you want a value at the moment an action runs.
The typical place is a notifier method or a widget callback:
class OrderApi {
Future<void> placeOrder(int totalCents) async {
// Send the order to a server.
}
}
@riverpod
OrderApi orderApi(Ref ref) => OrderApi();
@riverpod
class Checkout extends _$Checkout {
@override
FutureOr<void> build() {}
Future<void> submit() async {
final total = ref.read(cartTotalProvider);
final api = ref.read(orderApiProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() => api.placeOrder(total));
}
}submit runs because a user tapped a button. At that moment it needs the current total, so ref.read fits. If submit used ref.watch, it would be wrong for a different reason: Checkout would rebuild every time the total changed and reset its own state.
The generator infers checkoutProvider as an AsyncNotifierProvider because build returns FutureOr<void>.
The rule of thumb
| Situation | Use |
|---|---|
| Computing a provider's value from other providers | `ref.watch` |
| Building a widget's UI from provider state | `ref.watch` |
| Running code in a callback, such as `onPressed`, or in a notifier method | `ref.read` |
| Reacting to a change with a side effect, without rebuilding | `ref.listen` |
A common error is calling ref.read inside build or a provider body "to avoid extra rebuilds". The result is a value that silently goes stale: the UI shows the first value forever. If rebuilds are the concern, narrow them with select. Don't remove the dependency.
The opposite error is calling ref.watch in a callback. In a widget, Riverpod asserts in debug mode that ref.watch is only used while building. In a notifier method, a watch creates a dependency that is not tied to the build, which Riverpod does not support. Use ref.read there.
ref.listen: react without rebuilding
ref.listen(provider, callback) runs callback(previous, next) every time the provider's value changes. It does not rebuild the caller. Use it for side effects such as showing a SnackBar, navigating, or logging.
In a widget
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CheckoutButton extends ConsumerWidget {
const CheckoutButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen(checkoutProvider, (previous, next) {
if (next.hasError && !next.isLoading) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Order failed. Try again.')),
);
}
});
final checkout = ref.watch(checkoutProvider);
return FilledButton(
onPressed: checkout.isLoading
? null
: () => ref.read(checkoutProvider.notifier).submit(),
child: Text(checkout.isLoading ? 'Placing order...' : 'Place order'),
);
}
}This one widget uses all three methods. ref.listen shows the error message once per failure. ref.watch redraws the button label. ref.read starts the action. Putting the SnackBar logic in ref.watch would be wrong, because side effects inside build can run on every rebuild.
Inside a provider
A provider can also listen to another provider, and it can update its own state from the callback:
@riverpod
class LastAdded extends _$LastAdded {
@override
int? build() {
ref.listen(cartProvider, (previous, next) {
if (next.length > (previous?.length ?? 0)) {
state = next.last;
}
});
return null;
}
}Here LastAdded holds the price of the most recent cart addition. It does not rebuild when the cart changes. The callback assigns state directly, and build is not run again. That keeps the previous value available, which a watch-and-rebuild design would lose.
The previous argument is null the first time. Always guard for that, as the code does with previous?.length ?? 0.
Listening and the first value
By default, ref.listen fires only on changes after it is set up. It does not fire for the value that already exists. If you need the callback for the current value too, pass fireImmediately: true:
ref.listen(
cartProvider,
(previous, next) => print('Cart has ${next.length} items'),
fireImmediately: true,
);How ref interacts with provider lifetime
Providers from @riverpod are auto-dispose by default. They are disposed when nothing listens to them. Each ref.watch and ref.listen counts as a listener. A ref.read does not.
This has a practical effect. In Checkout.submit, ref.read(cartTotalProvider) returns a value without keeping cartTotalProvider alive. If the widget tree is not watching the total at that moment, the provider may be created, read and disposed straight away. The value you got is still valid. But if you need the provider to stay alive across the awaited call, watch it in build or mark it with keepAlive: true. The lifetime chapter covers that choice in detail.
A related rule: don't store ref and use it after the provider has been disposed. After disposal, calls to ref throw. If an async method might finish after the provider is gone, keep the provider watched by the UI during the operation.
Common errors
- Reading in
buildwithref.read. The value never updates. Replace it withref.watch, possibly withselect. - Watching in a callback. In widgets this triggers a debug assertion. Replace it with
ref.read. - Side effects in
ref.watch. Showing dialogs or navigating frombuildcan repeat on every rebuild. Move the logic toref.listen. - Watching
.notifierand expecting updates. The notifier object does not change, so no rebuild happens. Watch the provider itself for state. - Forgetting
previouscan benull. Guard it inref.listencallbacks. - Stale generated code. If
cartProviderorcheckoutProvideris flagged as undefined after you add a provider, rundart run build_runner buildagain, or keepwatchrunning.
Exercise
A provider unreadCount is declared as int unreadCount(Ref ref) => ref.read(messagesProvider).where((m) => !m.read).length;. The messages list updates, but the count in the UI never changes. What is wrong, and how do you fix it?
Show answer
ref.read creates no dependency, so unreadCount is computed once and never rebuilt. Change it to ref.watch(messagesProvider). To avoid recomputing for unrelated changes, use ref.watch(messagesProvider.select((messages) => messages.where((m) => !m.read).length)).
Exercise
You want to show a SnackBar whenever checkoutProvider enters an error state, and also redraw a button label based on the same provider. Which ref methods do you use for each task, and why must they be different?
Show answer
Use ref.listen for the SnackBar and ref.watch for the label. The SnackBar is a side effect that should run once per change, which ref.listen provides without rebuilding. The label is part of the UI that must be recomputed from state, which ref.watch provides. Putting the SnackBar in build through a watch would repeat it on every rebuild.