Use a scope and keep track of who owns it
Let ProviderScope make a container or pass one in. Use a Consumer to get WidgetRef in familiar Riverpod-style code, and decide which part of the app will dispose of the container.
Who disposes of the container?
The code that owns the container is responsible for disposing of it.
Container made by ProviderScope
ProviderScope(child: ...) disposes of the container it created when the scope is disposed, provided the container hasn't been replaced.
Container you pass in
With ProviderScope(container: c, ...), the caller needs to run c.dispose().
Scope without container ownership
You own cleanup for a container you give to UncontrolledProviderScope.
Clean up after a widget test
In a widget test, dispose of any ProviderContainer you passed in so its timers are cleaned up.
Choose a Consumer for your widget
All three options give you WidgetRef. Choose the one that matches the part of the UI you want to rebuild and whether it keeps local state.
When to use each widget
Consumer Use a builder to rebuild one part of the UI.
ConsumerWidget Use build(context, ref) in a stateless widget.
ConsumerStatefulWidget Read ref in ConsumerState and keep local state.
Use ConsumerStatefulWidget for local state
Use ConsumerState when a widget needs both WidgetRef and its own changing UI state.
class HomePage extends ConsumerStatefulWidget {
const HomePage({super.key});
@override
ConsumerState<HomePage> createState() => _HomePageState();
}
class _HomePageState extends ConsumerState<HomePage> {
bool expanded = false;
@override
Widget build(BuildContext context) {
final user = ref.watch(currentUser);
return Column(
children: [
Text('$user'),
Switch(
value: expanded,
onChanged: (v) => setState(() => expanded = v),
),
],
);
}
}
Where to go next
Test your providers
Test container cleanup, overrides, and async updates in unit tests and widget tests.
Learn to test providersAPI Reference
Look up the methods on ProviderScope, WidgetRef, and ProviderContainer.
Look up an API