Code Generation with riverpod_generator and @riverpod
Use the riverpod_generator annotations to produce type-safe providers without boilerplate.
Why Code Generation?
Before Riverpod 2.0, you picked the right provider type by hand: Provider, StateProvider, FutureProvider, StreamProvider, NotifierProvider, and so on. Choosing wrong meant rewrites.
The riverpod_generator package flips this around. You write a plain function or class and add the @riverpod annotation. The generator inspects your return type and produces the correct, fully type-safe provider for you.
- Less boilerplate — no manual provider declarations.
- Type-safe parameters — pass arguments without
.familygymnastics. - Auto-disposed by default — generated providers behave like
autoDispose.
Adding the Dependencies
Code generation needs both runtime and dev-time packages. riverpod_annotation ships the @riverpod annotation you use in source. riverpod_generator and build_runner run the build step that emits the .g.dart files.
A typical pubspec.yaml for a Flutter app looks like this.
dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^2.5.1
riverpod_annotation: ^2.3.5
dev_dependencies:
build_runner: ^2.4.11
riverpod_generator: ^2.4.0
custom_lint: ^0.6.4
riverpod_lint: ^2.3.10All lessons in this course
- From Provider to Riverpod: Migrating Legacy State
- Code Generation with riverpod_generator and @riverpod
- AsyncNotifier and FutureProvider Data Pipelines
- Provider Scoping, Overrides, and ProviderObserver