Sub topic 3
Writing Providers as Annotated Functions
Before you start
This chapter assumes that you know Dart functions, async and await, Future, and basic Riverpod usage with ProviderScope, ConsumerWidget, and ref.watch. You should also be able to run Dart commands from a terminal.
Riverpod code generation lets you describe a provider with a normal Dart function. An annotation tells the generator to create the provider declaration and its supporting code. This removes repeated provider boilerplate and keeps the provider logic close to the function that implements it.
Set up code generation
Add the runtime annotation package to your Flutter project. Add the generator and build_runner as development dependencies.
flutter pub add flutter_riverpod riverpod_annotation
flutter pub add --dev riverpod_generator build_runner
# Generate files once
dart run build_runner build
# Regenerate files whenever a source file changes
dart run build_runner watchThe generator reads annotated Dart files and creates files ending in .g.dart. The source file must include a matching part directive.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'greeting.g.dart';
@riverpod
String greeting(Ref ref) {
return 'Hello';
}The @riverpod annotation marks greeting for generation. After running build_runner, Riverpod creates greetingProvider. The generated provider can be watched in a widget:
class GreetingText extends ConsumerWidget {
const GreetingText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final message = ref.watch(greetingProvider);
return Text(message);
}
}The generated file is not something you normally edit by hand. Change the annotated source and run the generator again.
Predict the generated provider
The function's return type determines the provider's behavior.
| Function return type | Generated provider behavior |
|---|---|
| `String` | A synchronous `Provider<String>` |
| `Future<int>` | A `FutureProvider<int>` |
| `Stream<User>` | A `StreamProvider<User>` |
A function returning a Future becomes an asynchronous provider. Consumers receive an AsyncValue<int> when they watch it.
@riverpod
Future<int> answer(Ref ref) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return 42;
}
@riverpod
Stream<int> counter(Ref ref) async* {
for (var value = 1; value <= 3; value++) {
await Future<void>.delayed(const Duration(seconds: 1));
yield value;
}
}The generated names are based on the function names. These functions produce answerProvider and counterProvider.
Use ref to declare dependencies
The ref parameter connects one generated provider to another provider. Use ref.watch when the result should be recomputed when the dependency changes. This creates a dependency edge in Riverpod's graph.
@riverpod
String greeting(Ref ref) {
final name = ref.watch(nameProvider);
return 'Hello, $name';
}Use ref.read for a one-time read when the provider should not rebuild because of later changes. For example, an asynchronous operation can read a repository while starting a request.
@riverpod
Future<User> currentUser(Ref ref) async {
final repository = ref.read(userRepositoryProvider);
return repository.fetchCurrentUser();
}Use ref.listen when a provider needs to react to changes, such as logging or sending an event. Keep side effects limited and clear. In many widgets, listening belongs in the widget's ref.listen call instead.
Add parameters to create families
A function parameter turns the generated provider into a family. A family is a group of provider instances keyed by an argument.
@riverpod
Future<User> user(Ref ref, int id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
}The provider is now called with an argument:
class UserName extends ConsumerWidget {
const UserName({required this.id, super.key});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final user = ref.watch(userProvider(id));
return user.when(
data: (value) => Text(value.name),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
);
}
}userProvider(42) and userProvider(7) are separate cached instances. Each instance watches the same repository provider but stores the result for its own id.
Check your understanding
Exercise
What provider does an annotated function returning Future<List<String>> generate, and how would you call it if the function also accepted a String category parameter?
Show answer
It generates an asynchronous family provider, commonly named after the function with a Provider suffix. If the function were products(Ref ref, String category), you would watch productsProvider(category), which exposes an AsyncValue<List<String>>.