Flutter
ProviderScope
Wrap the root with ProviderScope.
ProviderScope
ProviderScope is the widget that wraps the app root and manages the lifecycle of all providers. It sits at the outermost layer of the runApp call.
void main() {
runApp(ProviderScope(child: MyApp()));
}
Every provider lives inside this scope.
Scope and lifecycle
ProviderScope manages the lifecycle of all providers inside it. When the app closes, providers are disposed. Multiple scopes can be used; the nearest one wins.
ProviderScope(
overrides: [],
child: MyApp(),
)
With overrides, providers can be overridden for testing.
Exercise Display name with ProviderScope
Declare a Provider<String> named isimP returning 'Riverpod'. Wrap the root with ProviderScope. In Ekrani ConsumerWidget, get the value with ref.watch(isimP) and display it. In main, call print('başladı').
Show example solution
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final isimP = Provider<String>((ref) => 'Riverpod');
void main() {
print('başladı');
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Ekrani());
}
}
class Ekrani extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final isim = ref.watch(isimP);
return Scaffold(body: Center(child: Text(isim)));
}
}
Test yourself
-
When is ProviderScope used?
- Only in StatelessWidgets
- Only in debug mode
- At the app root, outermost in the runApp call
- Only during testing
Show answer
At the app root, outermost in the runApp call — ProviderScope sits outermost in the runApp call and manages the lifecycle of all providers.
-
Pass overrides to ProviderScope
void main() {
runApp(ProviderScope(
____: [isimP.overrideWithValue('Test')],
child: MyApp(),
));
}
Show answer
void main() {
runApp(ProviderScope(
overrides: [isimP.overrideWithValue('Test')],
child: MyApp(),
));
}
-
ProviderScope parts
- ProviderScope
- Widget wrapping app root
- runApp
- Function that starts the app
- overrides
- Overrides providers for testing
- scope
- Environment where providers live
Next lesson: Summary - Riverpod basics