Sub topic 12
Pitfalls: Stale Generated Code, Unstable Arguments, and Missing Dependencies
Assume you know Dart async and await, Flutter widget basics, and basic Riverpod usage with ProviderScope, ConsumerWidget, and ref.watch. This chapter focuses on failures that appear after adopting @riverpod code generation, families, and scoped overrides.
Understand what the generator owns
The generator reads annotated Dart files and writes matching .g.dart files. Your source file must include a part directive whose name matches the source file:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'profile.g.dart';
@riverpod
Future<String> profileName(Ref ref) async {
return 'Ada';
}If this code is in profile.dart, the directive must be exactly part 'profile.g.dart';. A mismatch causes the generated provider to be missing or produces confusing analyzer errors.
Run the generator after adding or changing annotations:
dart run build_runner buildDuring development, watch for changes:
dart run build_runner watchThe generated file is build output. Do not edit it by hand. Your changes will be overwritten the next time the generator runs.
Recognize stale output
Generated code can become stale when you:
- Rename an annotated function but keep using the old provider name.
- Change a function from synchronous to asynchronous.
- Add or remove a family parameter.
- Rename the Dart file without updating its
partdirective. - Change generator or annotation package versions without rebuilding.
For example, changing this function:
@riverpod
String greeting(Ref ref) => 'Hello';to this function:
@riverpod
Future<String> greeting(Ref ref) async => 'Hello';changes the generated provider from a regular provider to a provider with asynchronous state. Callers may now need ref.watch(greetingProvider.future) or must handle AsyncValue<String>. Rebuild before diagnosing application code.
Keep family arguments stable
A parameter on an annotated provider creates a family. Riverpod uses the parameter value to identify each provider instance:
@riverpod
Future<List<String>> products(Ref ref, String category) async {
return ref.watch(productRepositoryProvider).search(category);
}productsProvider('books') and productsProvider('games') have separate state. Riverpod compares family arguments with equality. Primitive values such as String, int, and bool usually behave as expected.
A custom argument must implement consistent == and hashCode:
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;
}Without these overrides, two objects containing the same category are different by identity. Rebuilding a widget can then create a new family instance repeatedly. This can cause extra requests, lost cache state, and unexpected loading indicators.
Do not use mutable objects as family arguments. If a field changes after the object enters a provider key, its hashCode can change while Riverpod still stores the old key. Prefer immutable classes and const constructors.
Declare dependencies for scoped providers
A provider override applies only inside the ProviderScope where it is declared. A provider that reads the overridden value must declare that scoped dependency:
@Riverpod(dependencies: [])
Item currentItem(Ref ref) =>
throw UnimplementedError('Override currentItemProvider');
@Riverpod(dependencies: [currentItem])
String currentItemTitle(Ref ref) {
return ref.watch(currentItemProvider).title;
}A list item can supply a different value to each subtree:
ProviderScope(
overrides: [
currentItemProvider.overrideWith((ref) => items[index]),
],
child: const ItemTile(),
)The dependencies list tells Riverpod that currentItemTitleProvider can vary between scopes. Without it, Riverpod may treat the provider as belonging to an outer scope, so the child receives a value created from the wrong currentItemProvider.
A debugging sequence
When a generated or scoped provider behaves unexpectedly:
- Confirm the source file has the correct
partdirective. - Run
dart run build_runner build. - Check whether the provider type changed from synchronous to asynchronous.
- Inspect every family argument for immutability and equality.
- Confirm the override is above the widget that reads it.
- Add every scoped provider to the dependent provider's
dependencieslist. - Dispose test
ProviderContainerinstances after each test.
Exercise
A family receives a new ProductFilter(category: 'books') object on every rebuild and performs a new request each time. What should you check first?
Show answer
Check that ProductFilter is immutable and overrides both == and hashCode using the fields that define the provider key.