Sub topic 2
Setting up riverpod_generator and build_runner
This chapter adds code generation to a Flutter project and gets the first generated provider compiling. It assumes you know basic Riverpod (ProviderScope, ConsumerWidget, ref.watch), Dart async/await, and how to run commands in a terminal. It also assumes a Flutter project that already runs.
Why generate providers at all
With hand-written Riverpod, you pick the provider type yourself: Provider, FutureProvider, StreamProvider, NotifierProvider, AsyncNotifierProvider, and the .autoDispose and .family variants. Each choice means a different constructor and different type parameters. Families add a second type parameter for the argument.
Code generation moves that decision into the signature of an ordinary Dart function or class. You write the function, and a build tool writes the provider declaration. The generator picks the provider type from your return type and turns extra function parameters into family arguments. It also makes providers auto-dispose by default.
Generated providers behave the same as hand-written ones at runtime. ref.watch, ProviderScope, overrides and testing all work identically. The generator only changes how you declare providers.
The three packages
Three packages split the work.
| Package | Where it goes | Role |
|---|---|---|
| `flutter_riverpod` | dependencies | The runtime: `ProviderScope`, `ConsumerWidget`, `WidgetRef` |
| `riverpod_annotation` | dependencies | The `@riverpod` annotation and the base classes your generated code extends |
| `riverpod_generator` | dev_dependencies | The code generator itself, used only while building |
| `build_runner` | dev_dependencies | The tool that runs generators over your source files |
The generator is a development dependency because it never ships in your app. Only its output, the .g.dart files, is compiled into the app. riverpod_annotation must be a normal dependency because the generated code imports it.
Installing the packages
Run these from the project root:
flutter pub add flutter_riverpod riverpod_annotation
flutter pub add --dev riverpod_generator build_runner
# generate once
dart run build_runner build
# or regenerate on every save
dart run build_runner watchflutter pub add writes the latest compatible versions into pubspec.yaml. Afterwards the file should contain entries like these. Your version numbers will differ.
dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^3.0.0
riverpod_annotation: ^3.0.0
dev_dependencies:
build_runner: ^2.4.0
riverpod_generator: ^3.0.0Keep the three Riverpod packages on the same major version. If pub reports a version conflict, flutter_riverpod, riverpod_annotation and riverpod_generator usually disagree on the major version. Aligning them fixes it.
How the generator runs
build_runner scans your lib folder, hands each Dart file to the registered generators, and writes the results next to the source files. For Riverpod, the output file for greeting.dart is greeting.g.dart.
The generated file is not a separate library. It is a part of your file, so it can read private names from your file, and your file can use the names it defines. This is why the part directive is required.
Your first generated provider
Create lib/greeting.dart:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'greeting.g.dart';
@riverpod
String greeting(Ref ref) => 'Hello';
@riverpod
Future<int> answer(Ref ref) async => 42;Before you run the generator, the editor shows errors on the part line, because greeting.g.dart does not exist yet. Now run:
dart run build_runner buildAfter a few seconds, lib/greeting.g.dart appears. It declares two top-level variables:
greetingProvider, aProvider<String>, becausegreetingreturnsStringsynchronously.answerProvider, aFutureProvider<int>, becauseanswerreturns aFuture<int>.
The naming rule is: function name, then Provider. A function called greeting gives greetingProvider. The rule is mechanical, so you can predict names without opening the generated file.
You can read the generated file, but never edit it. The next build overwrites any change.
The part directive
The string in part '...' must match your file name with .g.dart in place of .dart. If you rename greeting.dart to welcome.dart, change the directive to part 'welcome.g.dart'; and rebuild. A mismatch gives the error "Target of URI hasn't been generated" or "Can't use 'welcome.g.dart' as a part". The first message appears when the file has not been generated yet. The second appears when the file exists but declares a different part-of owner.
The Ref parameter
Every functional provider takes a Ref as its first parameter. This is the handle you use to read other providers. Current generator versions accept the plain Ref type, as shown above. In older 2.x generator versions, the parameter type is a generated class named after the function, so greeting takes GreetingRef ref. If your project is on 2.x, use the generated name and expect a deprecation warning once you upgrade.
Using the provider in a widget
Generated providers are consumed exactly like hand-written ones. This is a complete app using greetingProvider:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'greeting.dart';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: HomePage());
}
}
class HomePage extends ConsumerWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final text = ref.watch(greetingProvider);
final answer = ref.watch(answerProvider);
return Scaffold(
body: Center(
child: Text(
answer.when(
data: (value) => '$text, the answer is $value',
loading: () => '$text, thinking...',
error: (error, _) => 'Failed: $error',
),
),
),
);
}
}The widget file imports greeting.dart, not greeting.g.dart. The part directive makes the generated names visible through the original file, so you never import a .g.dart file directly.
build versus watch
The two commands differ in when they run.
| Command | Behavior | Use it when |
|---|---|---|
| `dart run build_runner build` | One pass, then exit | Before committing, in CI, after pulling changes |
| `dart run build_runner watch` | Stays running and rebuilds changed files | During active development |
watch keeps a build cache in memory, so incremental rebuilds finish much faster than repeated build runs. Leave it running in a separate terminal while you edit.
Clearing conflicts
Occasionally build_runner refuses to overwrite a file and reports a conflicting output. This happens most often after switching branches or deleting generated files by hand. The fix is the flag below. It deletes the stale outputs and regenerates them:
dart run build_runner build --delete-conflicting-outputsThe flag is safe for generated files. It would be dangerous only if you had put hand-written code in a .g.dart file, which you should never do.
Generated files and version control
There are two common policies for .g.dart files.
- Commit them. A fresh clone builds with no extra step, and reviewers can read the generated diff. The cost is merge conflicts in generated files, and stale output if someone forgets to regenerate.
- Ignore them. Add
*.g.dartto.gitignoreand rundart run build_runner buildin CI and in your setup instructions. The repository stays clean, but every clone needs one extra command before it compiles.
Pick one for the whole team. Mixing the two is the usual source of "works on my machine" failures. If you ignore generated files, the CI job must run the build step before flutter analyze and flutter test, or both will fail on missing parts.
Common setup errors
Most first-run problems come down to a short list.
- "Target of URI hasn't been generated." You have not run the build yet, or the build failed. Run
dart run build_runner buildand read its output for errors. - Missing
partdirective. The build runs without errors, butgreetingProvideris undefined in the analyzer. Check that thepartline exists and names the right file. - Stale output after a signature change. You changed a function's return type or parameters, but the provider type in the editor did not change. Rebuild, or start
watch. The generated file does not update itself. - Annotation imported from the wrong package.
@riverpodcomes fromriverpod_annotation. Importing onlyflutter_riverpoddoes not provide it. - Generator in
dependencies. It still works, but it adds build-only code to your dependency tree. Keep it underdev_dependencies. - Version mismatch. An analyzer or Dart SDK conflict between
build_runner,riverpod_generatorand other generators, such asfreezedorjson_serializable. Update all of them together and runflutter pub upgrade.
Checking that it worked
A quick check is to add one more provider and see whether its name appears after a rebuild. Add this to greeting.dart with watch running:
@riverpod
String shout(Ref ref) {
final text = ref.watch(greetingProvider);
return text.toUpperCase();
}Within a second or two, shoutProvider becomes available. It is a Provider<String> that depends on greetingProvider. If the name stays undefined, check the terminal running watch for an error, since a failed build leaves the old output in place.
The next chapters build on this setup. The functional providers here are the simplest case. Later chapters add class-based providers, parameters that become families, and overrides.
Exercise
You rename lib/greeting.dart to lib/welcome.dart. The analyzer now reports errors on the part line, and greetingProvider is no longer found. What two things must you do to fix it?
Show answer
Change the directive to part 'welcome.g.dart'; so it matches the new file name, then run dart run build_runner build (adding --delete-conflicting-outputs if it reports a conflict with the old greeting.g.dart). The generator writes its output next to the source file with the matching name, so the old greeting.g.dart no longer belongs to any source file and can be deleted.
Exercise
A teammate clones the repository, which has *.g.dart in .gitignore, and runs flutter test. The tests fail with "Target of URI hasn't been generated". Why, and what should the CI job do?
Show answer
Ignored generated files are not in the clone, so the part directive points at a file that does not exist. The CI job must run dart run build_runner build before flutter analyze and flutter test. The teammate fixes it locally by running the same command once.
Exercise
You write @riverpod Future<int> answer(Ref ref) async => 42; and then @riverpod String greeting(Ref ref) => 'Hello';. Which provider type does each generate, and what are the names?
Show answer
answer generates answerProvider, a FutureProvider<int>, because it returns a Future. greeting generates greetingProvider, a Provider<String>, because it returns a plain value. The name is the function name followed by Provider.