Sub topic 3
Writing providers as annotated functions
This chapter assumes you can write a basic Riverpod provider by hand, read it with ref.watch in a ConsumerWidget, and have the packages and build_runner from the previous chapter installed. It covers how a plain function becomes a provider, which provider type you get, and what goes wrong most often.
The idea: the function body is the provider
A hand-written provider has two parts. One is the provider object, such as Provider<String> or FutureProvider<int>. The other is the callback that builds the value. With code generation you write only the callback, as a normal Dart function, and mark it with @riverpod. The generator reads your function and writes the provider object for you.
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;Three things must line up for this file to compile:
- The
part 'greeting.g.dart';directive must match the file name. The file isgreeting.dart, so the part file isgreeting.g.dart. - The function needs a
Refas its first parameter. Riverpod passes it in when it builds the provider. - You must run
dart run build_runner build(or leavewatchrunning) so the.g.dartfile exists.
Until the generator runs, your editor reports that greetingProvider is undefined. That is expected.
What the generator produces
The provider name comes from the function name plus the suffix Provider. greeting becomes greetingProvider, and answer becomes answerProvider. You never write that name yourself. You use it from other code, as you would use a hand-written provider.
The provider type depends on the function's return type:
| Return type of the function | Generated provider | Value seen with `ref.watch` |
|---|---|---|
| `String`, `int`, any plain type | `Provider<T>` | the value itself |
| `Future<T>` | `FutureProvider<T>` | `AsyncValue<T>` |
| `Stream<T>` | `StreamProvider<T>` | `AsyncValue<T>` |
So greetingProvider is a Provider<String>, and answerProvider is a FutureProvider<int>. The generator decides this from the declared return type, not from the keywords in the body. A function that returns a Future without async still gets a FutureProvider, and a function declared to return int is never a FutureProvider, even if you compute it slowly. Write the return type explicitly and read it as the contract.
The generated file is plain Dart. Roughly, it contains a constant of a generated provider class and a hash function that the generator uses to detect changes. You should read the file once to see what is there, but never edit it. The next build_runner run overwrites it.
Using generated providers in a widget
Generated providers are used exactly like hand-written ones. The widget below reads both providers from the first example. The FutureProvider yields an AsyncValue, so the widget handles loading and error states with when.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.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 {
await Future<void>.delayed(const Duration(seconds: 1));
return 42;
}
void main() {
runApp(const ProviderScope(child: MaterialApp(home: Home())));
}
class Home extends ConsumerWidget {
const Home({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final greeting = ref.watch(greetingProvider);
final answer = ref.watch(answerProvider);
return Scaffold(
body: Center(
child: answer.when(
data: (value) => Text('$greeting, the answer is $value'),
loading: () => const CircularProgressIndicator(),
error: (error, stack) => Text('Error: $error'),
),
),
);
}
}Save this as greeting.dart in lib/ so the part directive matches, and run the generator before you launch the app.
Streams
A function that returns a Stream becomes a StreamProvider. You can return an existing stream, or write the function as an async* generator and yield values.
@riverpod
Stream<int> ticker(Ref ref) async* {
var count = 0;
while (true) {
await Future<void>.delayed(const Duration(seconds: 1));
yield count++;
}
}ref.watch(tickerProvider) returns an AsyncValue<int> that holds the latest event. Riverpod cancels the subscription when the provider is disposed, which ends the loop at its next yield. By default that happens when no widget is listening to it. The chapter on provider lifetime covers this in detail.
Depending on other providers
Inside the function you read other providers through ref, the same way a hand-written provider does. Because the function is the provider's build callback, it runs again when a provider it watched changes.
@riverpod
String shout(Ref ref) {
final text = ref.watch(greetingProvider);
return text.toUpperCase();
}If greetingProvider ever produced a different value, shoutProvider would rebuild and notify its own listeners. The details of ref.watch, ref.read, and ref.listen come in the next chapter. For now, remember the rule that applies to every generated provider: use ref.watch inside the function body to depend on another provider.
Extra parameters make a family
Any parameter after ref changes what you generate. A function like user(Ref ref, int id) does not produce a plain provider. It produces a family, where you call userProvider(42) to get a separate provider instance per argument. Families have their own chapter. Here, note the consequence: adding a parameter to a function changes how every call site must read the provider. The call site ref.watch(userProvider) stops compiling and must become ref.watch(userProvider(42)).
Do not call the function yourself
The annotated function is still an ordinary Dart function, so nothing stops you from writing greeting(ref) in a widget. That call runs your function directly, with no caching, no listener tracking, and no rebuild when dependencies change. The result is a plain value that does not update. Always go through the generated provider.
// Wrong: runs the function once and bypasses Riverpod.
final text = greeting(ref);
// Right: reads the cached, tracked provider state.
final text2 = ref.watch(greetingProvider);Lifetime defaults
Providers created with @riverpod are auto-dispose by default. When the last listener goes away, the provider's state is thrown away, and the function runs again the next time somebody reads it. This is the opposite of a hand-written Provider, which keeps its state unless you add .autoDispose. If a function does expensive work and you see it run repeatedly as screens come and go, this default is the likely cause. Use @Riverpod(keepAlive: true) to keep the state. A later chapter covers that choice.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `greetingProvider` is undefined | The generator has not run, or it failed | Run `dart run build_runner build` and read its output for errors |
| "Can't find part file" or a uri error | `part` directive does not match the file name | Make it `<file name without .dart>.g.dart` |
| The provider type is not what you expected | The declared return type differs from what you assumed | Check the return type: `Future` gives `FutureProvider`, `Stream` gives `StreamProvider` |
| Changing the function seems to have no effect | Stale generated file | Re-run the generator, or keep `build_runner watch` running |
| A widget shows a value that never updates | You called the function directly | Use `ref.watch(greetingProvider)` instead |
| State resets when you leave a screen | Auto-dispose is the default | Add `keepAlive: true` if the state must survive |
If the generator fails with conflicting outputs, delete the stale .g.dart files or run dart run build_runner build --delete-conflicting-outputs. Commit your project's policy on whether .g.dart files are checked in, so that everyone on the team regenerates them the same way.
Choosing between functions and classes
A function provider fits when the value is computed from other providers and has no methods that change it. Reading configuration, fetching data, exposing a stream, and combining two providers are all good fits. When the state must change in response to user actions, such as a counter, a form, or a list you add to, use a class-based notifier. The next chapters cover that case. A good habit is to start with a function and move to a class only when you need a method that mutates state.
Summary of the working model
@riverpodon a function generates a provider named<function>Provider.- The return type chooses the provider kind: plain value,
Future, orStream. - The first parameter is
Ref. Extra parameters turn the provider into a family. - The
.g.dartfile comes frombuild_runner, and you never edit it. - You use the generated provider, never the function, from widgets and other providers.
Exercise
You write @riverpod Future<List<String>> names(Ref ref) async => ['Ada', 'Grace']; in names.dart. What name does the generated provider have, what is its type, what does ref.watch return for it, and which part directive must the file contain?
Show answer
The provider is namesProvider, a FutureProvider<List<String>>. ref.watch(namesProvider) returns an AsyncValue<List<String>>, so the widget must handle loading, error, and data states. The file needs part 'names.g.dart';.
Exercise
A teammate's widget calls final text = shout(ref); where shout is an annotated function that watches greetingProvider. The text never changes when the greeting changes. What is wrong, and how do you fix it?
Show answer
The call runs the plain function once and bypasses Riverpod, so there is no caching or dependency tracking. Replace it with ref.watch(shoutProvider), which rebuilds the widget when shoutProvider rebuilds.