Sub topic 17
A look at code generation with riverpod_generator
This chapter assumes you have read the earlier chapters. You should know Provider, Notifier, AsyncNotifier, family and autoDispose, and you should be comfortable with Dart generics and async/await. Code generation adds no new capabilities. It writes the same providers you have been declaring by hand.
Why generate providers
Hand-written providers need you to pick the right class for each case: Provider, FutureProvider, NotifierProvider, AsyncNotifierProvider, and the autoDispose and family variants of each. Parameterized providers add generic arguments that are easy to get wrong.
riverpod_generator removes that choice. You write a plain function or class and mark it with @riverpod. A build tool reads the annotation and the return type, then writes the matching provider into a separate file.
| You write | The generator produces |
|---|---|
| A function returning `T` | `Provider<T>` |
| A function returning `Future<T>` | `FutureProvider<T>` |
| A function returning `Stream<T>` | `StreamProvider<T>` |
| A class whose `build` returns `T` | `NotifierProvider` |
| A class whose `build` returns `Future<T>` | `AsyncNotifierProvider` |
| A function or `build` with extra parameters | A `family` provider |
| Any `@riverpod` annotation by default | An `autoDispose` provider |
Setting up the packages
Three packages are involved. riverpod_annotation provides the @riverpod annotation at runtime. riverpod_generator and build_runner run only during development.
dependencies:
flutter_riverpod: ^2.6.1
riverpod_annotation: ^2.6.1
dev_dependencies:
build_runner: ^2.4.0
riverpod_generator: ^2.6.1Run the generator once, or leave it running while you edit:
dart run build_runner build --delete-conflicting-outputs
dart run build_runner watch --delete-conflicting-outputsThe generator writes a file next to your source file with the extension .g.dart. Most teams add *.g.dart to version control or to .gitignore consistently. Choose one policy and apply it to the whole project.
flowchart LRThe diagram below shows the workflow from annotation to generated provider.
A function becomes a Provider
The first example from this tutorial, a read-only greeting, becomes one annotated function.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'greeting.g.dart';
@riverpod
String greeting(Ref ref) => 'Hello, Riverpod';Two lines are new. part 'greeting.g.dart'; tells Dart that the generated file is part of this library. Its name must match your file name plus .g. The annotation @riverpod marks the function for generation.
The generator names the provider after the function with Provider appended. A widget uses ref.watch(greetingProvider), exactly as before. Nothing about the consumer side changes.
A class becomes a Notifier
For mutable state you write a class that extends a generated base class. The base class has the name of your class with _$ in front.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
}The generated counterProvider behaves like the NotifierProvider<Counter, int> you wrote by hand. You still call ref.read(counterProvider.notifier).increment() in callbacks and ref.watch(counterProvider) in build methods. You no longer write the Counter.new tear-off or the two generic arguments.
Async state and mutations
The return type of build decides whether the result is synchronous or asynchronous. Returning a Future gives you an AsyncNotifier, and the state is an AsyncValue, so when works as before.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'todos.g.dart';
class Todo {
const Todo(this.id, this.title);
final int id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchAll();
Future<void> add(String title);
}
@Riverpod(keepAlive: true)
TodoRepository todoRepository(Ref ref) =>
throw UnimplementedError('Override todoRepositoryProvider');
@riverpod
class TodoList extends _$TodoList {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchAll();
}
Future<void> add(String title) async {
await ref.read(todoRepositoryProvider).add(title);
ref.invalidateSelf();
await future;
}
}The generated names are todoRepositoryProvider and todoListProvider. Overrides in tests work the same way, because todoRepositoryProvider.overrideWithValue(...) exists on the generated provider.
Families without the boilerplate
A hand-written family needs .family<String, int> and a second callback parameter. With the generator, any extra function parameter after ref turns the provider into a family.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'user_name.g.dart';
@riverpod
Future<String> userName(Ref ref, int id) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $id';
}You use it as ref.watch(userNameProvider(42)). Parameters can be positional or named, required or optional, and you can have several. Because the generated function takes the arguments directly, you get normal Dart type checking and named-argument syntax instead of a single generic type. In a class-based provider, the parameters go on build instead: Future<List<Todo>> build(String filter).
Lifetime changes by default
This is the most important behavioral difference from hand-written providers.
Use @Riverpod(keepAlive: true) for state that must outlive any widget that watches it. Typical examples are a repository, an authentication session or a settings object. The todoRepository provider above uses it for that reason. Leave the default for screen-scoped data such as a detail page's request.
Version notes and common errors
Older Riverpod versions generated a custom Ref subclass for each provider, such as GreetingRef or UserNameRef, and you had to write that type as the first parameter. From Riverpod 2.6 the plain Ref type is the recommended parameter. Code written with Ref works on 2.6 and later. If your project uses an older version, use the generated type instead.
Common errors:
- "Undefined name
_$Counter" or "Undefined namegreetingProvider". The generated file does not exist yet or is stale. Runbuild_runneragain. - "Part file doesn't exist". The
partdirective does not match the file name, or the generator has not run. - A hand-written provider and a generated one share a name. Rename one of them. The generator derives names from your declarations, so a clash is a compile error.
- State resets unexpectedly. The provider is
autoDisposeby default. AddkeepAlive: trueif it should persist. - Slow or noisy builds. Use
build_runner watchduring development andbuildin continuous integration.
When to use it
Generation is a convenience, not a requirement. Both styles are valid, interoperate, and can live in one project. Consider the generator when you have many families, because the syntax is much shorter, or when you want the provider type chosen from the return type automatically. Consider staying with hand-written providers when you want to avoid a build step, when your team is new to Riverpod and the generated files add confusion, or when the app has only a few providers.
The cost is a build step and generated files in the repository. The benefit is less boilerplate and fewer mismatched generic arguments.
Exercise
You convert a hand-written NotifierProvider that stores the logged-in user into a class annotated with plain @riverpod. After the change, the user is logged out whenever the login screen is closed. What happened, and how do you fix it?
Show answer
Generated providers are autoDispose by default. When no widget watches the provider, its state is disposed, so the user is lost. Fix it with @Riverpod(keepAlive: true) on the class so the state lives as long as the ProviderScope.
Exercise
Write the annotated function that creates a family provider named productProvider taking an int id and returning a Future<String>. What do you write in a widget to watch product 7?
Show answer
Write @riverpod Future<String> product(Ref ref, int id) async => 'Product $id'; with a part 'file.g.dart'; directive in the same file. In the widget, use ref.watch(productProvider(7)).