ProviderScope constructor
const
ProviderScope({
- Key? key,
- List<
Override> overrides = const [], - List<
ProviderObserver> ? observers, - ProviderContainer? parent,
- required Widget child,
A widget that stores the state of providers.
All Flutter applications using Riverpod must contain a ProviderScope at the root of their widget tree. It is done as followed:
void main() {
runApp(
// Enabled Riverpod for the entire application
ProviderScope(
child: MyApp(),
),
);
}
It optionally possible to specify overrides
to change the behavior of
some providers. This can be useful for testing purposes:
testWidgets('Test example', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
// override the behavior of repositoryProvider to provide a fake
// implementation for test purposes.
repositoryProvider.overrideWithValue(FakeRepository()),
],
child: MyApp(),
),
);
});
Similarly, it is possible to insert other ProviderScope anywhere inside the widget tree to override the behavior of a provider for only a part of the application:
final themeProvider = Provider((ref) => MyTheme.light());
void main() {
runApp(
ProviderScope(
child: MaterialApp(
// Home uses the default behavior for all providers.
home: Home(),
routes: {
// Overrides themeProvider for the /gallery route only
'/gallery': (_) => ProviderScope(
overrides: [
themeProvider.overrideWithValue(MyTheme.dark()),
],
),
},
),
),
);
}
See also:
- ProviderContainer, a Dart-only class that allows manipulating providers
- UncontrolledProviderScope, which exposes a ProviderContainer to the widget tree without managing its life-cycles.
Implementation
const ProviderScope({
super.key,
this.overrides = const [],
this.observers,
this.parent,
required this.child,
});