Sub topic 12
Pitfalls: stale generated code, unstable arguments, missing dependencies
This chapter assumes you can write @riverpod functions and classes, add parameters to make families, and use ProviderScope overrides as covered earlier in this tutorial. It collects the three mistakes that cause most confusing behavior with generated providers, and shows how to recognize and fix each.
Triage: which pitfall is it?
The symptoms differ by category, so start from what you see.
Pitfall 1: stale or missing generated code
Generated providers exist only after build_runner writes the .g.dart file. If that file is missing or out of date, your code refers to names that do not exist.
Typical symptoms
Undefined name 'greetingProvider'Classes can only extend other classesorUndefined class '_$Counter'- The
partline is underlined with "Target of URI doesn't exist" - A provider still has its old name or old parameters after you edited the function
Causes and fixes
| Cause | Fix |
|---|---|
| `build_runner` was never run | Run `dart run build_runner build` |
| The `part` directive is missing | Add `part 'greeting.g.dart';` below the imports |
| The `part` file name does not match the source file | Rename one so they match: `greeting.dart` needs `greeting.g.dart` |
| You renamed or moved a file | Update the `part` line and regenerate |
| Old outputs conflict with new ones | Run `dart run build_runner build --delete-conflicting-outputs` |
| You edit often and forget to regenerate | Keep `dart run build_runner watch` running |
The generated name comes from the function name, so renaming greeting to welcome changes greetingProvider to welcomeProvider. Every call site breaks until you regenerate and update it.
A missing riverpod_annotation import is a related mistake. The annotations come from package:riverpod_annotation/riverpod_annotation.dart, and that single import also exports Ref, so you do not need to import flutter_riverpod in a provider file for generation to work.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'greeting.g.dart'; // must match this file's name
@riverpod
String greeting(Ref ref) => 'Hello';Whether to commit generated files
Teams choose one of two policies.
- Commit
.g.dartfiles. The project compiles right after checkout, and reviewers can see generated changes. The cost is noisy diffs and merge conflicts in generated files. - Ignore
.g.dartfiles. Diffs stay clean. Every developer and every CI job must runbuild_runnerbefore analysis, tests, or builds.
Either policy works. The failure comes from mixing them: a CI job that analyzes code without a build step fails on a repository that ignores generated files.
When a merge conflict touches a .g.dart file, do not resolve it by hand. Take either side, then regenerate.
Pitfall 2: unstable family arguments
A family creates one provider instance per distinct argument. Riverpod decides whether two arguments are the same by comparing them with ==. If a new argument object is not equal to the previous one, Riverpod treats it as a different provider and builds it from scratch.
The failure
Here is a filter class that does not override ==:
class ProductFilter {
const ProductFilter({required this.category});
final String category;
}Used in a family provider and a widget:
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'products.g.dart';
@riverpod
Future<List<String>> products(Ref ref, ProductFilter filter) async {
debugPrint('building products for ${filter.category}');
await Future<void>.delayed(const Duration(milliseconds: 300));
return ['${filter.category} 1', '${filter.category} 2'];
}class ProductList extends ConsumerWidget {
const ProductList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
// A new ProductFilter object on every build, and no == override.
final products = ref.watch(
productsProvider(const ProductFilter(category: 'shoes')),
);
return products.when(
data: (items) => Text(items.join(', ')),
loading: () => const CircularProgressIndicator(),
error: (e, _) => Text('$e'),
);
}
}In this particular snippet the const constructor happens to produce one canonical object, so it works by accident. Remove const, or build the filter from a variable, and each build call creates a distinct object. The log then prints building products for shoes again and again, and the widget may stay in the loading state. The reason is the lifecycle:
- The widget builds and watches a new instance, which starts loading.
- The future completes and the widget rebuilds.
- The rebuild creates another non-equal
ProductFilter, so Riverpod looks up a different instance. - The first instance loses its listener and is auto-disposed. The new one starts loading.
The cycle never settles. With keepAlive: true the loop stops showing, but every abandoned instance stays in memory.
Fix: define value equality
import 'package:flutter/foundation.dart';
@immutable
class ProductFilter {
const ProductFilter({required this.category});
final String category;
@override
bool operator ==(Object other) =>
other is ProductFilter && other.category == category;
@override
int get hashCode => category.hashCode;
}You can also write == and hashCode with package:equatable or generate them with freezed. Whichever you use, include every field in both methods. If hashCode ignores a field that == compares, or the other way round, you get subtle duplicate or shared instances.
Which argument types are safe
| Argument type | Safe? | Note |
|---|---|---|
| `int`, `String`, `bool`, `double` | Yes | Compared by value |
| `enum` values | Yes | Each value is a single instance |
| Records such as `(int, String)` | Yes | Compared by value, field by field |
| Class with `==` and `hashCode` | Yes | You maintain these methods |
| `List`, `Set`, `Map` | No | Compared by identity, not contents |
| Functions and closures | No | A new closure is a new object |
| `BuildContext`, widgets | No | Not value types, and they can be disposed |
Passing a list is the most common surprise. productsProvider([1, 2]) creates a new list each time. Either wrap the list in a class that compares contents, or pass a value such as a joined string or a sorted set of IDs stored in a class with correct equality.
Floating-point arguments deserve caution too. Two values that look the same after rounding may differ in the last bits, so they create separate instances. Round or convert to an integer before passing them.
Find unstable arguments
Put a debugPrint at the top of the provider body, as in the example above. Each build of a distinct instance prints one line. If the same arguments print repeatedly while the screen is idle, the arguments are not equal. Fix == before you look for any other cause.
Pitfall 3: missing dependencies for scoped providers
A scoped provider is one you override in a nested ProviderScope, such as a per-item value in a list. Riverpod must know which other providers depend on a scoped one, so that they rebuild inside each scope instead of being shared from the root.
You declare this with the dependencies argument of @Riverpod.
@Riverpod(dependencies: [])
Item currentItem(Ref ref) =>
throw UnimplementedError('Override currentItemProvider in a ProviderScope');
@Riverpod(dependencies: [currentItem])
String currentItemTitle(Ref ref) => ref.watch(currentItemProvider).title;dependencies: [] on currentItem marks it as scoped, with no scoped dependencies of its own. dependencies: [currentItem] on currentItemTitle says it reads a scoped provider.
What goes wrong without the list
If you write currentItemTitle with plain @riverpod and no dependencies, Riverpod has no record that it depends on currentItem. The title provider then behaves like a normal global provider.
- It is built against the root container, where
currentItemhas no override. You typically get theUnimplementedErrorfrom the default body. - Or, if a root-level override exists, every item shows the same title, because a single shared instance serves the whole app.
Make the analyzer find it
The riverpod_lint package reports a missing dependencies entry during analysis, so you do not discover it at runtime. It runs through custom_lint.
flutter pub add --dev custom_lint riverpod_lintEnable the plugin in analysis_options.yaml:
analyzer:
plugins:
- custom_lintThen run dart run custom_lint, or rely on the IDE integration. Add the entries the lint asks for, then run build_runner again, since the generated code changes with the list.
Scope placement errors
Even with a correct dependencies list, an override only reaches widgets below the ProviderScope that declares it.
- Scope too high. If you override
currentItemProvideronce above theListView, all items share one value. Put theProviderScopeinsideitemBuilder, one per item. - Scope too low. A widget that sits outside the item subtree, for example a header, cannot read the item's value. It reads the root, which throws.
- Scope created in a place that rebuilds. The override function runs again when the scope widget is rebuilt with new overrides. Keep the values you pass stable, such as
items[index]from a list that is not reallocated on every frame.
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ProviderScope(
overrides: [
currentItemProvider.overrideWith((ref) => items[index]),
],
child: const ItemTile(),
);
},
)Inside ItemTile, ref.watch(currentItemTitleProvider) now returns the title of that row's item.
Other mistakes that look similar
These are not specific to generation, but they show up with the same symptoms.
ref.readinsidebuild. The provider reads once and never updates when its dependency changes. Useref.watchin provider bodies and widgetbuildmethods.ref.watchin a callback. InonPressedand similar handlers, useref.read. Watching there is wrong and the lint flags it.- Using
refafter anawaitin a disposed provider. An auto-dispose provider can be disposed while a future is pending. Checkref.mountedwhere your Riverpod version provides it, or avoid touchingrefafter the gap. - Expecting
keepAliveto survive an app restart. It keeps state in memory while the container lives. It does not persist anything to disk.
Checklist before you commit
dart run build_runner buildfinishes without errors, andpartlines match their files.- Every family argument is a primitive, an enum, a record, or a class with
==andhashCode. - Every provider that reads a scoped provider lists it in
dependencies. dart run custom_lintreports nothing for provider dependencies.- Each scoped override sits in a
ProviderScopethat is an ancestor of every widget reading it.
Exercise
A screen calls ref.watch(searchProvider(SearchQuery(text: 'boots'))) and the loading spinner never stops. The log shows "searching boots" printing many times per second. SearchQuery has a final String text field and no other members. What is wrong, and what do you change?
Show answer
SearchQuery does not override == and hashCode, so each build creates an object that Riverpod sees as a different family argument. Every rebuild starts a new provider instance, the old one is auto-disposed, and the future never settles on one instance. Add == (comparing text) and hashCode (using text.hashCode) to SearchQuery, or use a type that already has value equality, such as a String or a record.
Exercise
After renaming the function userName to displayName in profile.dart, the analyzer reports Undefined name 'userNameProvider' in three widgets, and displayNameProvider is also undefined. List the steps to fix it.
Show answer
Run dart run buildrunner build (add --delete-conflicting-outputs if it reports conflicts) so profile.g.dart contains displayNameProvider. Confirm the part 'profile.g.dart'; line is present and matches the file name. Then change the three widgets from userNameProvider to displayNameProvider. Keeping buildrunner watch running avoids the stale file in the future.
Exercise
In a ListView, every row shows the title of the first item, even though each row wraps its child in ProviderScope with currentItemProvider.overrideWith. currentItemTitle is declared with plain @riverpod and reads currentItemProvider. What is the fix?
Show answer
currentItemTitle depends on a scoped provider but does not declare it, so one shared instance is built outside the row scopes. Declare @Riverpod(dependencies: [currentItem]) on currentItemTitle, mark currentItem with @Riverpod(dependencies: []), and run buildrunner again. Each row's ProviderScope then gets its own currentItemTitle. Running dart run customlint with riverpod_lint would have flagged the missing entry.