Sub topic 1
Where hand-written providers get repetitive
Riverpod providers hold state and dependencies outside the widget tree. Writing them by hand works well at first. As an app grows, you repeat the same decisions many times: which provider class to use, which generic types to spell out, and how to chain modifiers such as autoDispose and family. This chapter recaps hand-written providers and shows where that repetition appears. The rest of the tutorial replaces it with the @riverpod annotation and code generation.
Prerequisites
This chapter assumes you already know:
- Dart fundamentals, including
async/await,Future, andStream. - Flutter widget basics:
StatelessWidget,BuildContext, andListView. - Basic Riverpod usage: wrapping the app in
ProviderScope, reading state in aConsumerWidget, and callingref.watch. - How to run
dartandfluttercommands from a terminal.
You do not need any code generation experience. The setup comes in the next chapter.
A quick recap: providers, ref, and ProviderScope
Three pieces make up the Riverpod model you will keep using.
- A provider is a declaration that describes how to build a value. It is usually a top-level
finalvariable. The provider does not hold the value. It is a key that Riverpod uses to create and cache the value. - A
refis the handle a provider receives when it builds. Through it, a provider reads other providers (ref.watch,ref.read,ref.listen). Widgets get aWidgetReffromConsumerWidgetand use it the same way. - A
ProviderScopeis the widget that stores provider state. You place one at the root of the app. Everything below it reads and shares the same cached values.
Here is a small, complete app that uses all three:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello');
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: GreetingText())));
}
}
class GreetingText extends ConsumerWidget {
const GreetingText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final greeting = ref.watch(greetingProvider);
return Text(greeting);
}
}greetingProvider is only a description. The first ref.watch makes the nearest ProviderScope build the value and store it. Later watchers receive the stored value.
The provider types you write by hand
Without code generation, you pick a provider class that matches what you want to expose. These are the common choices:
| You want to expose | Provider class you write |
|---|---|
| A synchronous, read-only value | `Provider<T>` |
| A value that arrives later | `FutureProvider<T>` |
| A stream of values | `StreamProvider<T>` |
| Synchronous state with methods that change it | `NotifierProvider<N, T>` |
| Async state with methods that change it | `AsyncNotifierProvider<N, T>` |
Each class has its own constructor shape, and you must get the generic parameters right. The next sections show what that costs.
Read-only and async values
final greetingProvider = Provider<String>((ref) => 'Hello');
final answerProvider = FutureProvider<int>((ref) async => 42);These two lines are short. The choice of Provider versus FutureProvider depends on the return type, and you make it by hand each time. If answerProvider later becomes synchronous, you rewrite the declaration and every place that handled an AsyncValue.
State with methods
A counter that can be incremented needs a class and a provider that points at it:
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);The type int appears twice: once in Notifier<int> and once in NotifierProvider<Counter, int>. If you change one and forget the other, the compiler reports the mismatch, but you still have to edit two places for one idea.
Dependencies between providers
A provider reads another provider through ref. Here a repository is built once and then used by a provider that fetches a user:
class User {
const User({required this.id, required this.name});
final int id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(int id);
}
class HttpUserRepository implements UserRepository {
@override
Future<User> fetchUser(int id) async {
// A real app would call an API here.
return User(id: id, name: 'User $id');
}
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => HttpUserRepository(),
);Declaring the repository as a provider is what makes it replaceable. You will use that in later chapters to swap in a fake during tests.
Where the repetition shows up
The examples above are small. The repetition appears once you add parameters, lifetime control, and more providers.
Families repeat type arguments
A family is a provider that takes an argument and keeps a separate state for each distinct value. By hand, you add .family and spell out two type arguments, the result type and the argument type:
final userProvider = FutureProvider.family<User, int>((ref, id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
});Here int is written as a type argument and then again as the closure's id parameter, which Dart infers. The shape of the function is already in the declaration, and the provider restates it.
Modifiers pile up
State from a modifier-free provider can stay in memory for the life of the scope. To release it when no widget listens, you add the autoDispose modifier. Combined with family, the declaration grows:
final userProvider = FutureProvider.autoDispose.family<User, int>((ref, id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
});The modifiers must be chained in the right place. The type parameters shift with each modifier you add. Every provider in the app repeats the same ceremony.
Class-based providers with arguments are the hardest
In Riverpod 2.x, a class-based provider that takes an argument needs a different base class and a different provider constructor from the plain version. The exact classes depend on your Riverpod version, so check the documentation for the one you use. The cost is the same in every version. You must remember which pairing of class and provider applies, and a wrong pairing becomes a compile error you then have to decode.
Names and types are your job
Each provider needs a variable name, usually somethingProvider. The type of the exposed value appears in a generic parameter. Nothing links the function body to the provider's type, apart from the type checker.
A decision you make over and over
For each new piece of state, you walk through the same questions:
- Is the value synchronous, a
Future, or aStream? - Does it need methods that change its state?
- Does it take an argument?
- Should it be disposed when unused?
Your answers determine which class, which modifiers, and which type arguments you write.
Every branch in this diagram is information the function or class could already carry. A function that returns Future<User> is asynchronous. A function with an int id parameter takes an argument. The provider declaration restates facts your code already states.
What code generation changes
The riverpod_generator package reads an annotated function or class and writes the provider declaration for you. The @riverpod annotation replaces the choices from the diagram:
- The return type picks
Provider,FutureProvider, orStreamProvider. - A class that extends the generated base class becomes a Notifier or AsyncNotifier provider.
- Extra function parameters become the family arguments.
- Providers are auto-dispose by default, and
keepAlive: trueopts out.
This is the earlier userProvider in annotated form:
@riverpod
Future<User> user(Ref ref, int id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
}The generator produces a provider called userProvider from the function name. You write one function, and the type arguments, the .family call, and the autoDispose modifier are produced for you. The next chapters cover each part of that mapping in detail.
What you give up, and what you gain
Code generation has costs, and you should weigh them:
- A build step. You run
build_runner, and generated.g.dartfiles must be up to date. Stale generated files cause confusing errors, and a later chapter covers them. - Two extra packages besides
flutter_riverpod:riverpod_annotationfor the annotation andriverpod_generatorwithbuild_runneras development tools. - A less visible declaration. The provider's real type lives in a generated file, so you read it less often.
In return, you get:
- Less code per provider and fewer type arguments to keep in sync.
- Families written as ordinary function parameters, with the compiler checking the argument types for you.
- One uniform way to write every kind of provider.
For a small app with a handful of providers, hand-written declarations are fine. The benefit grows with the number of providers, especially families and notifiers.
Chapter checklist
Before moving on, make sure you can do the following:
- Explain what a provider, a
ref, and aProviderScopeeach do. - Choose the hand-written provider class for a given kind of state.
- Name three things you must repeat by hand that the annotation will infer: the provider class, the type arguments, and the modifiers.
- State one cost of code generation, such as the build step.
Exercise
A teammate writes final productsProvider = FutureProvider.autoDispose.family<List<Product>, String>((ref, category) async => ...);. List the pieces of information this declaration carries, and say which of them an annotated function Future<List<Product>> products(Ref ref, String category) would already contain.
Show answer
The declaration carries four facts. The value is asynchronous (FutureProvider), the result type is List<Product>, the provider takes a String argument (.family and the second type argument), and the state is released when unused (autoDispose). The annotated function already states the first three through its Future<List<Product>> return type and its String category parameter. Auto-dispose is the default for @riverpod providers, so it needs no extra text either.
Exercise
Why is it useful that userRepositoryProvider is a provider rather than a plain global object, even though both would let userProvider fetch a user?
Show answer
Because Riverpod stores provider state in a ProviderScope and lets you replace how a provider is built. A test or a subtree can substitute a different UserRepository, such as a fake, without changing userProvider. A plain global object would be fixed and could not be replaced that way.