Sub topic 12
Parameterized providers with family
This chapter covers family, the modifier that turns one provider declaration into many independent provider states, one per argument. It assumes you know Provider, FutureProvider, ref.watch and AsyncValue.when from earlier chapters, and that you are comfortable with == and hashCode in Dart.
The problem family solves
A plain provider holds one value for the whole app. Many screens need a value that depends on an input. A detail page needs the user with a given id. A price label needs a currency. A search results list needs the current query.
You could create a provider per id, but the ids are only known at runtime. You could keep the id in a separate provider and have the data provider watch it. That works for a single "currently selected" id, but it breaks down when two widgets need different ids at the same time.
family solves this. You declare the provider once, and it takes an argument. Each distinct argument gets its own provider state, its own loading and error status, and its own lifetime.
Declaring and reading a family
Add .family to the provider type and give two type arguments. The first is the value type and the second is the argument type. The creation function receives the argument after ref.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final userNameProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $id';
});
void main() {
runApp(const ProviderScope(child: MaterialApp(home: UserPage())));
}
class UserPage extends StatelessWidget {
const UserPage({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Column(
children: [
UserTile(id: 1),
UserTile(id: 2),
UserTile(id: 1),
],
),
);
}
}
class UserTile extends ConsumerWidget {
const UserTile({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final name = ref.watch(userNameProvider(id));
return name.when(
data: (value) => ListTile(title: Text(value)),
error: (error, stackTrace) => ListTile(title: Text('Error: $error')),
loading: () => const ListTile(title: Text('Loading...')),
);
}
}Calling userNameProvider(id) does not run the function. It returns a provider object that identifies one entry in the family. The first ref.watch on that object creates the state. Later watches with an equal argument find the existing state.
In the example, the two tiles with id: 1 share one state, so the fake request runs once for id 1 and once for id 2. Three widgets are on screen, but only two states exist.
How arguments are compared
Riverpod looks up the state by the argument, using == and hashCode. This is the main source of family bugs, so it is worth understanding.
- Primitives such as
int,String,booland enums compare by value. They work with no extra effort. - Dart 3 records compare structurally, so a record of equal fields is an equal argument.
- Lists, maps and sets compare by identity unless you wrap them. A new list literal in
buildis a different argument on every rebuild. - Your own classes compare by identity unless you override
==andhashCode.
When the argument is a custom class, define value equality:
import 'package:flutter_riverpod/flutter_riverpod.dart';
class SearchQuery {
const SearchQuery(this.text, {this.includeArchived = false});
final String text;
final bool includeArchived;
@override
bool operator ==(Object other) =>
other is SearchQuery &&
other.text == text &&
other.includeArchived == includeArchived;
@override
int get hashCode => Object.hash(text, includeArchived);
}
final searchResultsProvider =
Provider.family<List<String>, SearchQuery>((ref, query) {
const all = ['apple', 'apricot', 'banana'];
return [
for (final item in all)
if (item.contains(query.text)) item,
];
});For several simple values, a record is a shorter alternative to a class. You write Provider.family<String, ({String currency, int cents})> and call it with price((currency: 'EUR', cents: 250)). Records get correct equality for free.
Family takes exactly one argument
A family accepts a single argument. To pass several values, bundle them into a record or a class with value equality, as shown above. Do not pass a Map or List literal for this purpose, since those compare by identity.
Family and autoDispose
The userNameProvider example uses autoDispose together with family. The two modifiers are independent, and combining them is common. The order in the declaration is FutureProvider.autoDispose.family.
Without autoDispose, every argument ever used keeps its state until the ProviderScope is disposed. For a family keyed by an id or a search string, that is a slow memory leak. Each new argument adds an entry that is never freed.
With autoDispose, the state for one argument is released when nothing listens to it. Navigating away from the detail page for user 42 drops the state for 42 only. Other arguments are unaffected. Coming back to that page runs the provider function again, so the user sees a loading state again.
The next chapter covers lifecycle in detail, including how to keep a state alive on purpose.
Invalidating one entry or the whole family
ref.invalidate works at two levels:
ref.invalidate(userNameProvider(42))resets only the state for argument 42. A watching widget sees a refresh.ref.invalidate(userNameProvider)resets every state in the family at once.
Use the narrow form after you mutate one record. Use the wide form after an event that makes all cached results stale, such as a user logging out.
class RefreshButton extends ConsumerWidget {
const RefreshButton({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
return IconButton(
icon: const Icon(Icons.refresh),
onPressed: () => ref.invalidate(userNameProvider(id)),
);
}
}Using family inside other providers
A provider can watch a family entry, which lets you compose values. The argument can come from another provider, from a field you hold, or from a constant.
final selectedUserIdProvider = StateProvider<int>((ref) => 1);
final selectedUserNameProvider = Provider.autoDispose<AsyncValue<String>>((ref) {
final id = ref.watch(selectedUserIdProvider);
return ref.watch(userNameProvider(id));
});When selectedUserIdProvider changes, selectedUserNameProvider recomputes and starts watching the entry for the new id. The old entry loses its listener, and autoDispose frees it.
Choosing between family and a selected-id provider
| Situation | Better choice |
|---|---|
| Several widgets show different ids at the same time | `family` |
| One "current" item for the whole screen | A plain provider that watches a selected-id provider |
| Argument is a free-form value such as a search string | `family` with `autoDispose` |
| Argument is a list or map | Wrap it in a class or record with value equality |
Common mistakes
- Passing an argument without value equality, which creates a new state on every rebuild.
- Forgetting
autoDisposeon a family keyed by user input, so states pile up. - Calling
ref.read(userNameProvider(id))inbuildinstead ofref.watch. The widget then never updates. - Expecting
ref.invalidate(userNameProvider(42))to refresh other ids. It affects only 42. - Creating the argument inside the provider function from mutable data, so two equal-looking calls differ.
Exercise
A screen builds ref.watch(searchProvider(['dart', 'flutter'])) inside build, where searchProvider is a FutureProvider.autoDispose.family<List<String>, List<String>>. The page shows a spinner forever. What is wrong, and how do you fix it?
Show answer
The list literal is a new object on every rebuild. Lists compare by identity, so each rebuild is a different argument. It creates a fresh provider state that starts in the loading state. The state then completes and triggers a rebuild, which creates yet another state, so the spinner never settles. Fix it by passing an argument with value equality. Use a record such as (String, String), or wrap the terms in a class that overrides == and hashCode, or use a single joined String.
Exercise
You have orderProvider = FutureProvider.autoDispose.family<Order, int>(...). After the user edits order 7, which call refreshes only that order, and which call refreshes every cached order?
Show answer
ref.invalidate(orderProvider(7)) refreshes only order 7. ref.invalidate(orderProvider) invalidates every state in the family.