Sub topic 11
Scoped providers for subtrees such as list items
This chapter assumes you can write @riverpod functions, use ref.watch in a ConsumerWidget, and have seen ProviderScope(overrides: ...) replace a dependency at the root of an app. Here you will use the same mechanism lower in the widget tree, so that each subtree gets its own value of a provider.
The problem: passing the same item down the tree
Consider a ListView of items. Each row is a small tree of widgets: a tile, a title, a favorite button, a price label. Every widget needs the row's Item. The usual solution is to pass item through constructors, and that becomes tedious as the row grows. Worse, a const widget cannot be created if it takes a changing argument, so the row rebuilds more than it needs to.
A family such as itemProvider(id) could solve part of this, but every widget would still need the id. Riverpod offers another route: declare one provider, currentItemProvider, that means "the item of the row I am in", and give that provider a different value inside each row. Widgets in the row call ref.watch(currentItemProvider) and never receive a constructor argument.
How scoping works
A ProviderScope creates a container of provider state. The ProviderScope at the top of the app is the root. When you place another ProviderScope deeper in the tree and list a provider in its overrides, that provider gets separate state for everything below that nested scope. Providers outside the subtree still see the root's value.
The root value of currentItemProvider is deliberately useless. It throws. If a widget reads the provider outside any row, it fails loudly instead of showing wrong data.
Declaring a scoped provider
A scoped provider is an ordinary provider with two conventions. Its default implementation throws, and it declares dependencies in the annotation.
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'current_item.g.dart';
@immutable
class Item {
const Item({required this.id, required this.title});
final int id;
final String title;
}
@Riverpod(dependencies: [])
Item currentItem(Ref ref) =>
throw UnimplementedError('Override currentItemProvider in a ProviderScope');
@Riverpod(dependencies: [currentItem])
String currentItemTitle(Ref ref) => ref.watch(currentItemProvider).title;Two details matter here.
dependencies: []oncurrentItemtells Riverpod that this provider may be overridden in a nested scope and that it needs nothing else to be scoped. Without the annotation argument, the generator creates a provider that is only expected to be overridden at the root.dependencies: [currentItem]oncurrentItemTitletells Riverpod that this provider reads a scoped provider. Riverpod therefore builds a separatecurrentItemTitlestate in every scope that overridescurrentItem.
Providing a value to each row
Put a nested ProviderScope in the itemBuilder. The child widget needs no constructor parameters, so it can be const.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'current_item.dart';
void main() {
runApp(const ProviderScope(child: MaterialApp(home: ItemListPage())));
}
class ItemListPage extends StatelessWidget {
const ItemListPage({super.key});
static const items = [
Item(id: 1, title: 'Milk'),
Item(id: 2, title: 'Eggs'),
Item(id: 3, title: 'Bread'),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ProviderScope(
key: ValueKey(items[index].id),
overrides: [
currentItemProvider.overrideWith((ref) => items[index]),
],
child: const ItemTile(),
);
},
),
);
}
}
class ItemTile extends ConsumerWidget {
const ItemTile({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final title = ref.watch(currentItemTitleProvider);
return ListTile(title: Text(title));
}
}Run dart run build_runner build first so current_item.g.dart exists.
ItemTile is a const widget and it does not know which row it is in. It reads currentItemTitleProvider, which reads currentItemProvider, which Riverpod resolves to the nearest scope that overrides it.
Why the key matters
ListView.builder can reuse and rebuild row widgets as the list scrolls or changes. A scope's override factory runs when the provider is first read in that scope. If the same ProviderScope element were later reused for a different item, it could keep showing the old one. Giving the scope a ValueKey based on the item's identity makes Flutter create a new scope for a new item.
What the dependencies list does
The dependencies list is how Riverpod learns which providers have to be recreated when a scope overrides something they use. This table shows what each provider does for a row in the example.
| Provider | Declared dependencies | State in the root scope | State in a row scope |
|---|---|---|---|
| `currentItemProvider` | none (`[]`) | Throws `UnimplementedError` | The row's `Item` from the override |
| `currentItemTitleProvider` | `currentItem` | Throws, because it reads the root `currentItemProvider` | `title` of that row's `Item`, held separately per row |
A scoped provider is not a global that gets mutated. Each scope holds its own state, and Riverpod disposes the state when the scope leaves the tree.
The failure when dependencies are missing
Suppose you forget to declare the dependency.
@riverpod
String currentItemTitle(Ref ref) => ref.watch(currentItemProvider).title;This compiles. At runtime, currentItemTitleProvider is a normal root-level provider. When ItemTile watches it, Riverpod creates its state in the root container. That state reads the root currentItemProvider, which throws UnimplementedError. The nested scope never matters, because currentItemTitleProvider was never told to follow it.
This is the most common scoped-provider mistake. The symptom is the "Override currentItemProvider in a ProviderScope" error even though you did add an override, and the override is in the right place.
Widgets are different. A ConsumerWidget that calls ref.watch(currentItemProvider) finds the nearest scope through the widget tree, so widgets declare nothing.
The riverpod_lint package, part of the custom_lint toolchain, reports a missing or surplus dependencies entry (the rule is provider_dependencies; the exact name has varied between releases). Enable it, because the runtime error does not tell you which provider forgot its list.
Scoped providers and families
Scoping and families solve related problems, and the choice between them is a design decision.
| Question | Family such as `itemProvider(id)` | Scoped `currentItemProvider` |
|---|---|---|
| Where does the value come from? | Any widget that knows the argument | The nearest enclosing scope |
| Is state shared between widgets? | Yes, for equal arguments | Only within one scope |
| Does each widget need an argument? | Yes | No |
| Can it load data on its own? | Yes, `build` can fetch by `id` | Only if you override it with something that does |
The two combine well. A common design is a family that fetches the data, and a scoped provider that holds only the id of the current row.
@Riverpod(dependencies: [])
int currentItemId(Ref ref) =>
throw UnimplementedError('Override currentItemIdProvider in a ProviderScope');
@Riverpod(dependencies: [currentItemId])
Future<User> currentUser(Ref ref) {
final id = ref.watch(currentItemIdProvider);
return ref.watch(userProvider(id).future);
}userProvider(id) is the family from earlier in this tutorial. Because it is read from inside currentUser, its state is shared by every widget that asks for the same id, while currentUser itself is scoped per row. Do not list the family in dependencies here. It reads only root providers, so it is not scoped and does not need to be declared.
Testing a scoped widget
A widget that reads a scoped provider is easy to test, since the test only has to supply the override.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'current_item.dart';
import 'item_list.dart';
void main() {
testWidgets('ItemTile shows the title of the current item', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
currentItemProvider.overrideWithValue(
const Item(id: 1, title: 'Milk'),
),
],
child: const MaterialApp(home: Scaffold(body: ItemTile())),
),
);
expect(find.text('Milk'), findsOneWidget);
});
}This test overrides at the root, not in a nested scope. That is enough, because currentItemTitleProvider declares its dependency and so picks up the override from the nearest scope, which is the root here. You can test ItemTile without building the whole list.
Edge cases and gotchas
- Do not override a provider that did not opt in. Overriding a provider in a nested scope when it has no
dependenciesargument is an error in Riverpod 2.x. Overrides on a nestedProviderScopeare only allowed for providers that declaredependencies. A rootProviderScopecan override anything. - Keep override lists stable. The set of overridden providers in one
ProviderScopemust not change between rebuilds. You can change a value, but you cannot add or remove a provider from the list. - Scoped state is disposed with the scope. When a row scrolls out of a
ListView.builderand its scope is removed, every provider state held in that scope is disposed. Anything the row loaded must be loaded again when the row comes back. Move expensive data to a root-level provider, such as a family keyed by id, if you want it to survive scrolling. - Scopes are not navigation-aware. A route pushed with
Navigator.pushfrom a row is not inside that row's scope unless you wrap it again. The route is built under theNavigator, not under the row widget. Pass a newProviderScopewith the same override, or pass the id as a route argument. - Notifiers can be scoped too. A class-based provider with
dependenciescan be overridden withoverrideWithreturning a new notifier instance. Scoped notifiers keep separate state per scope, which suits per-row expanded or selected flags.
Debugging checklist
When a scoped provider throws or shows the wrong value, check these in order.
- Is the
ProviderScopewith the override an ancestor of the widget that reads the provider? - Does every provider between the widget and the overridden provider list its dependency in
dependencies? - Did you rerun
dart run build_runner buildafter changingdependencies? The list is read by the generator, so a stale.g.dartfile ignores your edit. - Does the nested scope have a key that changes when the item changes?
Exercise
A teammate adds @riverpod String currentItemTitle(Ref ref) => ref.watch(currentItemProvider).title; with no dependencies. Each row has a nested ProviderScope that overrides currentItemProvider. Every row shows the UnimplementedError message. Why does this happen, and what is the fix?
Show answer
Without dependencies, currentItemTitleProvider is a root-level provider. Its state is created in the root container, where currentItemProvider still throws, so the row overrides are never consulted. Change the annotation to @Riverpod(dependencies: [currentItem]) and rerun dart run build_runner build. Then Riverpod creates the title state separately in each scope that overrides currentItemProvider.
Exercise
You show a list of products and each row needs the product's reviews, loaded from a repository by product id. Sketch which providers you would make, which one is scoped, and which one is a family.
Show answer
Make a family reviews(Ref ref, int productId) that fetches and caches reviews per id. Make a scoped @Riverpod(dependencies: []) int currentProductId(Ref ref) that throws by default and is overridden in a nested ProviderScope per row. Make @Riverpod(dependencies: [currentProductId]) Future<List<Review>> currentReviews(Ref ref) that watches currentProductIdProvider and returns ref.watch(reviewsProvider(id).future). Row widgets watch currentReviewsProvider without any constructor argument, and the reviews survive in the family cache while the scoped state is tied to the row.