Sub topic 16
Common mistakes and best practices
This chapter collects the errors that most often appear in Riverpod code and the habits that prevent them. It assumes you have read the earlier chapters and know ref.watch, ref.read, Notifier, AsyncNotifier, family and autoDispose. It also assumes you are comfortable with Dart generics and async code.
Reading providers the wrong way
Using ref.read inside build
ref.read returns the current value once and does not subscribe to changes. In a build method, that produces a widget that shows the first value forever.
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 CountLabel extends ConsumerWidget {
const CountLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
// Wrong: this never rebuilds when the counter changes.
// final count = ref.read(counterProvider);
// Right: watch the value in build.
final count = ref.watch(counterProvider);
return Text('$count');
}
}Using ref.watch inside a callback
The opposite mistake is calling ref.watch in onPressed or another event handler. In debug mode Riverpod throws an assertion, because a subscription made outside build would never be cleaned up correctly. The rule has two parts:
- Use
ref.watchwhile building, to get values that should trigger a rebuild. - Use
ref.readin callbacks, to run a method once.
FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
)Reading the notifier with watch
ref.watch(counterProvider.notifier) is legal, but it rarely does what people expect. The notifier object is created once, so watching it never causes a rebuild when the state changes. Read the notifier with ref.read in callbacks and watch the state itself.
Mistakes in how state changes
Mutating state in place
A Notifier announces a change when you assign a new value to state. Calling add on a list that is already stored in state changes the contents but assigns nothing, so listeners are never told.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Tags extends Notifier<List<String>> {
@override
List<String> build() => [];
// Wrong: mutates the existing list, so no widget rebuilds.
void addInPlace(String tag) => state.add(tag);
// Right: assign a new list.
void add(String tag) => state = [...state, tag];
void remove(String tag) =>
state = [for (final t in state) if (t != tag) t];
}
final tagsProvider = NotifierProvider<Tags, List<String>>(Tags.new);Treat state as immutable. Use copyWith-style methods, spread operators and List.of so that every update produces a fresh object.
Changing other providers during build
A provider's build method should only compute a value from its inputs. If it modifies another provider, for example by assigning to that provider's state, Riverpod throws an error about modifying a provider while the widget tree is building. The same happens when a widget does this in its own build. Move the change into an event handler, or make the target a derived provider so it never needs to be set by hand.
Creating providers inside build
A provider is a global declaration. If you write final p = Provider((ref) => 1); inside build, you create a new provider on every rebuild, and any state it held is lost. Declare providers as top-level final variables, as in every example so far.
Mistakes with async providers and lifetimes
Ignoring errors and loading states
AsyncValue keeps the previous data while it reloads. Reading .value directly and assuming it is non-null is a common source of crashes. Prefer when, or switch on the value, so that data, error and loading are all handled. If you want to show old data during a refresh, check isLoading and hasValue explicitly.
Unbounded growth in families
A family creates one state per distinct argument. Without autoDispose, each state lives until the container is disposed. A screen that watches userProvider(id) for hundreds of ids keeps all of them in memory.
Argument equality also matters. Riverpod finds the right state by comparing arguments with ==. If you pass an object that does not override ==, every call creates a new provider state. Use ints, strings, records, or classes with proper equality.
Caching with keepAlive
autoDispose drops state as soon as nobody listens, which can cause repeated network calls when the user moves between screens. ref.keepAlive() lets you keep the state for a limited time.
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final userNameProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
// Keep the result for one minute after the last listener leaves.
final link = ref.keepAlive();
final timer = Timer(const Duration(minutes: 1), link.close);
ref.onDispose(timer.cancel);
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $id';
});Registering ref.onDispose for the timer ensures it is cancelled if the provider is disposed earlier, for example when the container itself is torn down.
Putting side effects in build
Showing a snackbar, navigating or logging from a widget's build method runs that code on every rebuild. Use ref.listen for these reactions. It calls your callback with the previous and next values, and it does not rebuild the widget on its own.
Mistakes with rebuilds and structure
Watching more than you need
If a widget needs one field of a larger object, watching the whole object rebuilds it for unrelated changes. Use select:
final name = ref.watch(profileProvider.select((p) => p.name));Do not apply select everywhere by default. It adds noise and is only worth it when profiling or reasoning shows needless rebuilds. A small widget that is cheap to rebuild does not need it.
Putting logic in widgets
Widgets that call http or database code directly are hard to test. Put that code in a repository class, expose the repository through a Provider, and let notifiers depend on it with ref.watch(repositoryProvider). This is the structure that makes overrides in tests possible.
Forgetting to override in tests
A repository provider that throws UnimplementedError by design fails loudly if a test forgets to override it. That is the intended behavior. In tests, also dispose the container with addTearDown(container.dispose), otherwise listeners and timers from one test can leak into the next.
final container = ProviderContainer(overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
]);
addTearDown(container.dispose);Best practices at a glance
| Practice | Reason |
|---|---|
| Declare providers as top-level `final` variables | They are definitions, not instances, so they must not be recreated. |
| `watch` in `build`, `read` in callbacks, `listen` for side effects | Each method matches one moment in the widget lifecycle. |
| Keep state immutable and assign new objects | Assignment is what notifies listeners. |
| Prefer `autoDispose` for per-screen and per-argument state | It frees memory and avoids stale data. |
| Hide I/O behind repositories | You can replace them with fakes in tests. |
| Handle every `AsyncValue` state | Loading and error states are normal, not edge cases. |
| Use `select` when a widget needs part of a value | It narrows rebuilds without extra providers. |
A short review checklist
Before you merge Riverpod code, scan it for these points:
- Every
ref.readinbuildhas a good reason, such as a one-time read that should not subscribe. - No
ref.watchappears insideonPressed,onTapor other callbacks. - No notifier method mutates
statein place. - Every family has a plan for disposal, either
autoDisposeor an explicitkeepAlive. - Tests create a
ProviderContainer, apply overrides, and dispose it.
Exercise
A Notifier<List<String>> has the method void add(String s) { state.add(s); }. The list view that watches the provider never updates after you call add. Why, and how do you fix it?
Show answer
state.add(s) mutates the list that is already stored, and nothing is assigned to state, so the notifier never tells its listeners that the value changed. Assign a new list instead: state = [...state, s];.
Exercise
A screen watches userNameProvider(User(id: 1)), where User is a plain class without ==. Memory grows and the data reloads on every rebuild. What is happening, and what are two ways to fix it?
Show answer
Each User(id: 1) is a new, unequal object, so Riverpod treats every call as a different family argument and creates a new provider state each time. Fix it by passing the id (userNameProvider(1)), or by giving User value equality through == and hashCode. Adding autoDispose also limits how long the unused states live.