Sub topic 16
Common Mistakes and Best Practices
This chapter assumes you know Dart classes, futures, async and await, Flutter’s build method, and the difference between setState and lifted state. The examples use Riverpod 2 with Notifier and AsyncNotifier.
Use the Right `ref` Method
A common mistake is choosing ref.read when the widget should rebuild. Use ref.watch for values needed during build. Riverpod then rebuilds the widget when that provider changes. Use ref.read for one-time actions, such as a button callback. Use ref.listen for side effects, such as a snackbar or navigation.
| Method | Main purpose | Typical location |
|---|---|---|
| `ref.watch` | Read a value and rebuild when it changes | `build` |
| `ref.read` | Read a value once or call a notifier method | Event callbacks |
| `ref.listen` | React without rebuilding for that reaction | Side-effect logic |
class SaveButton extends ConsumerWidget {
const SaveButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final saving = ref.watch(saveProvider).isLoading;
return ElevatedButton(
onPressed: saving
? null
: () => ref.read(saveProvider.notifier).save(),
child: Text(saving ? 'Saving...' : 'Save'),
);
}
}Do not call ref.read in build just to display state. The widget will show the value once and then become stale.
Keep Provider State Immutable
When a provider contains an object or collection, replace the state with a new value. Do not mutate a list in place and expect Riverpod to detect the change.
class TagsNotifier extends Notifier<List<String>> {
@override
List<String> build() => const [];
void add(String tag) {
state = [...state, tag];
}
}select can reduce rebuilds, but it depends on meaningful value changes. Select a small, stable field, and avoid returning a mutable object that changes internally.
Handle Every Async State
AsyncValue represents loading, data, or error. Do not access .value without deciding what should happen when loading or when an error occurs.
class ItemsView extends ConsumerWidget {
const ItemsView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final items = ref.watch(itemsProvider);
return items.when(
loading: () => const CircularProgressIndicator(),
error: (error, stack) => Text('Load failed: $error'),
data: (values) => ListView(
children: [for (final value in values) ListTile(title: Text(value))],
),
);
}
}AsyncNotifier should own loading and mutation logic. The widget should mainly render the state and send user actions to the notifier.
Understand Lifetimes and Families
A family creates a separate provider instance for each argument. Use stable, meaningful arguments. Avoid passing a newly created object on every build unless that object has correct equality.
autoDispose releases state when nothing listens to the provider. This is useful for screen-specific data, but it can cause a request to restart when a screen is temporarily removed. Keep long-lived session state in a provider without autoDispose.
Test the Provider Graph
Provider logic should be testable without rendering widgets. Override external dependencies, such as repositories, with fakes. This keeps tests deterministic and avoids network calls.
Exercise
A widget displays a provider value but never updates. Which mistake is most likely, and what should replace it?
Show answer
The widget probably used ref.read in build. Replace it with ref.watch so the widget subscribes to provider changes.