Sub topic 2
ProviderScope and the provider container
This chapter assumes you know Dart classes and generics, Flutter's StatelessWidget and build method, and the idea of lifting state up. You should also have seen a provider declared as a top-level final variable. Here you will learn where provider state actually lives and how ProviderScope connects it to your widgets.
Providers are recipes, not storage
A provider such as final counterProvider = NotifierProvider<Counter, int>(Counter.new); is a global constant. It describes how to build a value, but it holds no value. Because it holds no state, a global declaration does not behave like a global variable.
The state lives in a provider container, which is an object of type ProviderContainer. You can think of it as a map from each provider to its current state. The first time something reads a provider, the container runs the provider's creation function, stores the result, and returns the stored value on later reads.
What ProviderScope does
ProviderScope is a widget from flutter_riverpod. It does three things:
- It creates a
ProviderContainerwhen it is first inserted into the tree. - It makes that container available to every descendant widget, which is how
WidgetReffinds the container. - It disposes the container when the widget is removed from the tree, which releases every provider's state.
You normally place one ProviderScope around the whole app:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final greeting = ref.watch(greetingProvider);
return MaterialApp(
home: Scaffold(body: Center(child: Text(greeting))),
);
}
}The scope goes above MyApp, and above MaterialApp. Any widget that reads a provider must sit below a ProviderScope.
Using a container without Flutter
ProviderContainer belongs to the plain Dart riverpod package. It does not need widgets. This makes the container's behavior easy to see in a console program. Add riverpod to your dependencies and run this file with dart run:
import 'package:riverpod/riverpod.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
final configProvider = Provider<String>((ref) {
print('configProvider created');
return 'production';
});
void main() {
final a = ProviderContainer();
final b = ProviderContainer();
print('containers created');
print(a.read(configProvider));
print(a.read(configProvider));
a.read(counterProvider.notifier).increment();
print('a: ${a.read(counterProvider)}');
print('b: ${b.read(counterProvider)}');
a.dispose();
b.dispose();
}The program prints:
containers created
configProvider created
production
production
a: 1
b: 0This output shows two behaviors:
- Providers are lazy.
configProvideris not created when the containers are created. It is created on the firstread. The secondreadreuses the stored value, so the creation message prints once. - Containers are isolated. Incrementing the counter in container
adoes not change containerb. The same provider object is a separate state entry in each container.
ProviderScope compared with ProviderContainer
| Row | `ProviderScope` | `ProviderContainer` |
|---|---|---|
| Package | `flutter_riverpod` | `riverpod` (re-exported by `flutter_riverpod`) |
| Kind | Widget | Plain Dart object |
| Created by | Flutter, when the widget enters the tree | Your code |
| Disposed by | Flutter, when the widget leaves the tree | You, by calling `dispose()` |
| Typical use | The root of an app | Unit tests, scripts, and code outside the widget tree |
If you create a ProviderContainer yourself, you must also dispose it. A forgotten dispose() leaves listeners and timers running.
Overriding providers at the scope
Both ProviderScope and ProviderContainer accept an overrides list. An override replaces how a provider builds its value, but only inside that container. This is the standard way to supply a value that is not known until the app starts, such as configuration read from disk.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final appNameProvider = Provider<String>(
(ref) => throw UnimplementedError('Override appNameProvider'),
);
void main() {
runApp(
ProviderScope(
overrides: [appNameProvider.overrideWithValue('Todo Planner')],
child: const NameApp(),
),
);
}
class NameApp extends ConsumerWidget {
const NameApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp(
title: ref.watch(appNameProvider),
home: const Scaffold(body: Center(child: Text('Ready'))),
);
}
}The default builder throws on purpose. If you forget the override, the app fails the first time it reads the provider, and the message names the missing override. A silent default value would hide the mistake.
Nested scopes
You can place a ProviderScope deeper in the tree. A nested scope creates a child container that has its own overrides.
- A provider that the nested scope overrides gets its own state inside that subtree.
- A provider that the nested scope does not override is looked up in the parent container, so both scopes share that state.
Nested scopes are useful when a subtree needs its own value for one provider. Examples include a list item that needs its own item id, or a preview screen that needs a different theme. Most apps need only the single root scope.
Lifetime and hot reload
The container's lifetime follows its ProviderScope widget. Three practical consequences follow:
- Provider state survives widget rebuilds, navigation, and hot reload, because the scope stays in the tree.
- Hot restart and full app restarts create a new scope, so all provider state is lost.
- If a rebuild gives the scope a different key, or inserts a different widget type at the scope's position, Flutter replaces the scope. The old container is disposed and all of its state is lost.
Common errors
No ProviderScope found. If you call runApp(const MyApp()) and MyApp reads a provider, Riverpod throws an error saying no ProviderScope was found. Wrap the root widget as shown earlier.
Scope placed too low. A ProviderScope only serves its descendants. If you put it inside one screen, widgets outside that screen, such as the MaterialApp or other routes, cannot read the providers. Keep the main scope at the root.
Creating a container inside build. Calling ProviderContainer() in a build method creates a new empty container on every rebuild. State appears to reset. Create containers only in main, in tests, or in other code that runs once.
Reading state before it exists in tests. A test that reads a provider with a throwing default, such as appNameProvider, must pass the override to its container.
Exercise
A widget reads counterProvider, and you call runApp(MaterialApp(home: CounterPage())) with no ProviderScope. What happens, and what is the fix? Then explain why two separate ProviderContainer objects that read the same counterProvider can hold different values.
Show answer
Reading the provider throws an error saying no ProviderScope was found, because WidgetRef cannot locate a container. The fix is to wrap the root widget: runApp(const ProviderScope(child: MyApp())). The provider is only a key. Each container stores its own state for that key, so incrementing the counter in one container does not change the value in the other.
Exercise
You declare final apiUrlProvider = Provider<String>((ref) => throw UnimplementedError());. Write the ProviderScope call in main that sets its value to 'https://example.com'.
Show answer
runApp(ProviderScope(overrides: [apiUrlProvider.overrideWithValue('https://example.com')], child: const MyApp()));