Sub topic 7
Families: turning parameters into provider instances
This chapter assumes you can write a basic @riverpod function provider and run build_runner, as covered in the earlier chapters. You should also be comfortable reading an AsyncValue in a ConsumerWidget. Here you will see how an extra function parameter turns one provider declaration into many independent provider instances.
The problem a family solves
A plain provider holds one value. greetingProvider has one state, shared by every widget that watches it. Many screens need data that depends on an input, such as the user with a given id, the posts on a given page, or the products in a given category.
Without a family you would need one provider per input, which does not work when the input is only known at runtime. A family fixes this. It is a provider that takes an argument, and Riverpod keeps a separate state for each distinct argument.
Before code generation, you wrote this with the .family modifier, for example FutureProvider.family<User, int>(...). With riverpod_generator you add parameters to the annotated function and the generator does the rest.
Adding a parameter to a function provider
Any parameter after ref makes the provider a family. This complete file shows a user repository and a family built on it.
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'user.g.dart';
@immutable
class User {
const User({required this.id, required this.name});
final int id;
final String name;
}
class UserRepository {
Future<User> fetchUser(int id) async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return User(id: id, name: 'User $id');
}
}
@riverpod
UserRepository userRepository(Ref ref) => UserRepository();
@riverpod
Future<User> user(Ref ref, int id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
}The generator produces userProvider, but it is no longer a provider you can pass straight to ref.watch. It is a family object. You call it with an argument, and the call returns the actual provider for that argument:
final asyncUser = ref.watch(userProvider(42));userProvider(42) and userProvider(7) are two different providers. Each has its own loading, data, and error state, and each runs fetchUser separately.
The return type still decides the provider type. Future<User> gives a FutureProvider-style provider, so asyncUser is an AsyncValue<User>. Parameters change only how many instances exist, not what kind of provider each one is.
How instances are stored
Riverpod keeps a registry per ProviderContainer. A family instance is identified by the family plus its arguments. When you call ref.watch(userProvider(42)), Riverpod looks for an existing instance with that identity. If one exists, you get its current state. If not, it creates the instance and runs the function.
Two consequences follow from this model:
- Widgets that ask for the same argument share one fetch and one cached result. You do not need to coordinate between them.
- Instances are independent, so changing or invalidating one does not touch the others.
The userRepositoryProvider in the diagram is a plain provider, so it exists once and every user instance reads the same repository.
Several parameters, named and optional
A generated family can take more than one parameter. Positional, named, required, and defaulted parameters all work.
@riverpod
Future<List<String>> postTitles(
Ref ref, {
required int userId,
int page = 1,
}) async {
// Replace with a real repository call.
return ['Post ${page}0 by $userId', 'Post ${page}1 by $userId'];
}You pass the arguments in the same shape as the function signature:
final titles = ref.watch(postTitlesProvider(userId: 3, page: 2));The identity of an instance is the whole set of arguments. postTitlesProvider(userId: 3) and postTitlesProvider(userId: 3, page: 1) have equal arguments, because page defaults to 1. They resolve to the same instance.
Families with class-based providers
A class-based provider becomes a family the same way, through the parameters of build. Each instance gets its own notifier object and its own state.
@riverpod
class UserNote extends _$UserNote {
@override
String build(int userId) => '';
void update(String text) => state = text;
}In a widget you pick the instance, then pick the value or the notifier:
final note = ref.watch(userNoteProvider(1));
ref.read(userNoteProvider(1).notifier).update('Call back on Monday');Here userNoteProvider(1) and userNoteProvider(2) hold separate strings. Updating the note for user 1 does not rebuild widgets that watch user 2.
Note that the parameter goes on build, not on the class constructor. The notifier class is created by the framework, and build is the entry point that receives the arguments.
A complete usage example
This widget shows one user. The id is a field of the widget, and it flows straight into the family.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'user.dart';
class UserTile extends ConsumerWidget {
const UserTile({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncUser = ref.watch(userProvider(id));
return switch (asyncUser) {
AsyncData(:final value) => ListTile(title: Text(value.name)),
AsyncError(:final error) => ListTile(title: Text('Error: $error')),
_ => const ListTile(title: Text('Loading...')),
};
}
}If the parent rebuilds and passes a different id, the tile watches a different instance. The old instance is released and the new one starts loading. You do not write any code for that switch.
You can also depend on a family instance from inside another provider. The dependent provider can take its own parameter and forward it:
@riverpod
Future<String> userGreeting(Ref ref, int id) async {
final user = await ref.watch(userProvider(id).future);
return 'Welcome back, ${user.name}';
}The .future getter returns the Future<User> of that instance. Awaiting it lets the new provider wait for data without handling AsyncValue manually.
Lifetime of family instances
Providers from @riverpod are auto-dispose by default, and families follow the same rule for each instance. An instance is disposed when nothing listens to it any more. userProvider(42) can be disposed while userProvider(7) stays alive because a widget still watches it.
The table shows how this plays out.
| Situation | Result |
|---|---|
| Two widgets watch `userProvider(42)` | One shared instance, one fetch |
| The last widget watching `userProvider(42)` is removed | That instance is disposed, and the next watch fetches again |
| A widget watches `userProvider(7)` at the same time | Unaffected, because its instance is separate |
| Family declared with `@Riverpod(keepAlive: true)` | Every instance stays cached, even with no listeners |
With keepAlive: true on a family, each distinct argument that is ever requested stays in memory until the container is disposed or the instance is invalidated. For a family with an unbounded set of arguments, such as search text, this is a memory leak in practice. Keep auto-dispose, which is the default, unless you have a reason to cache.
Refreshing and invalidating
You can target one instance or the whole family.
// Rebuild only the instance for id 42.
ref.invalidate(userProvider(42));
// Rebuild every instance of the family.
ref.invalidate(userProvider);
// Invalidate one instance and read the new value immediately.
final fresh = await ref.refresh(userProvider(42).future);Passing the family itself, without arguments, invalidates all of its instances. This is useful after a login change or a bulk update. Passing a specific call invalidates only that instance. An invalidated instance with no listeners is disposed. One with listeners rebuilds.
Failure modes to watch for
These mistakes are common when you first use families.
- Forgetting the argument.
ref.watch(userProvider)does not compile as anAsyncValueread, becauseuserProvideris the family, not an instance. Call it with its arguments. - Creating a new key on every build. If the argument is an object without value equality, each rebuild creates a new instance that starts loading again. The result is a loading spinner loop or repeated network calls. The next chapter covers this.
- Unbounded keep-alive. As explained above,
keepAlive: trueon a family with many possible arguments grows memory. - Expecting shared state between instances. If two screens must share one value, they must pass the same arguments. If they need a value that does not depend on an argument, use a provider with no parameter.
- Stale generated code. If you add or change a parameter and see errors on
userProvider(...), rerundart run build_runner build. The.g.dartfile still describes the old signature.
Summary of the model
A family has the same declaration style as a normal provider plus parameters. Riverpod uses the arguments as part of the provider identity, keeps one state per identity, shares it between all listeners, and disposes it independently under the usual auto-dispose rules. You select an instance by calling the family like a function, then use it like any other provider.
Exercise
You declare @riverpod Future<Product> product(Ref ref, String sku). Widget A calls ref.watch(productProvider('A1')). Widget B calls ref.watch(productProvider('A1')), and Widget C calls ref.watch(productProvider('B2')). How many times does the function body run on first load, and what happens when Widget A and Widget B are both removed from the tree while Widget C stays?
Show answer
The body runs twice: once for the instance with 'A1' (shared by A and B) and once for 'B2'. When A and B are removed, the 'A1' instance has no listeners and, because @riverpod is auto-dispose by default, it is disposed. The 'B2' instance stays alive because Widget C still watches it.
Exercise
A screen shows a dashboard for the logged-in account. After the user switches accounts, you want to discard the cached userProvider data for every id, not just the current one. Which call do you use, and how does it differ from ref.invalidate(userProvider(42))?
Show answer
Call ref.invalidate(userProvider) with no arguments. It invalidates every instance of the family. ref.invalidate(userProvider(42)) invalidates only the instance for id 42 and leaves the others cached.