Sub topic 17
A look at code generation with riverpod_generator
Prerequisites and purpose
This chapter assumes Dart classes, generics, async and await, Flutter widgets, and basic Riverpod providers. Code generation means writing a smaller source file and using a tool to create repetitive Dart code from it.
riverpod_generator creates provider declarations from annotations. The generated providers still use the same Riverpod concepts: ProviderScope, ref.watch, ref.read, Notifier, and AsyncNotifier.
Configure the generator
Add matching versions of these packages to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^2.5.1
riverpod_annotation: ^2.3.5
dev_dependencies:
build_runner: ^2.4.9
riverpod_generator: ^2.4.0Run the generator with:
dart run build_runner build --delete-conflicting-outputsDuring development, use:
dart run build_runner watch --delete-conflicting-outputsThe --delete-conflicting-outputs option removes old generated files that would otherwise prevent the build.
Generate a synchronous provider
Create lib/counter.dart:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
}The part directive connects this file to counter.g.dart. The generator creates _$Counter and counterProvider. Do not edit the generated file. Regenerate it whenever the annotated source changes.
A widget uses the generated provider like any manually declared provider:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'counter.dart';
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
body: Center(child: Text('$count')),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}ref.watch rebuilds the widget when the counter changes. ref.read obtains the notifier for an event callback.
Generate families and asynchronous providers
A parameter in an annotated function or build method creates a family. Each argument gets separate provider state:
@riverpod
Future<String> userName(Ref ref, int userId) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $userId';
}The generated provider is called with an argument:
final name = ref.watch(userNameProvider(42));For asynchronous mutable state, extend the generated AsyncNotifier base class:
@riverpod
class TodoList extends _$TodoList {
@override
Future<List<String>> build() async {
return ['Read the Riverpod documentation'];
}
Future<void> add(String title) async {
final current = await future;
state = AsyncData([...current, title]);
}
}Widgets still receive an AsyncValue<List<String>>, so they should handle loading, data, and error states.
How generation fits together
Code generation reduces boilerplate, but it does not change provider behavior. Choose it when a project benefits from consistent declarations, generated families, and compile-time checks. Manual providers can remain simpler for small constants or dependency bindings.
Exercise
What does adding an argument to an annotated provider declaration do?
Show answer
It generates a family, so each argument value can have separate provider state, such as userNameProvider(42).