Sub topic 9
Overriding providers with ProviderScope
This chapter assumes you can write @riverpod functions and read them with ref.watch in a ConsumerWidget. It also assumes you know what a family is. You will learn how ProviderScope overrides replace the way a provider is built, which override method fits each provider type, and how overrides behave when scopes are nested.
What an override does
A provider declaration says how to build a value. An override replaces that recipe for everything that lives under a particular ProviderScope. Code that calls ref.watch(clockProvider) doesn't change. It receives whatever the nearest scope says clockProvider produces.
This gives you a seam for dependencies. Your code depends on an abstraction exposed through a provider. The app's main supplies the real implementation, and tests or previews supply a fake.
Overrides are useful in three situations:
- Replacing a dependency such as a repository, HTTP client or clock with a fake.
- Injecting a value that can only be created asynchronously before the app starts, such as a loaded
SharedPreferencesinstance. - Giving a subtree its own value for a provider, such as one list item. Later chapters cover this "scoped" case.
A complete example
The program below defines a Clock abstraction and a provider for it. The app is started with an override that returns a fixed time.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'main.g.dart';
abstract class Clock {
DateTime now();
}
class SystemClock implements Clock {
@override
DateTime now() => DateTime.now();
}
class FixedClock implements Clock {
FixedClock(this.value);
final DateTime value;
@override
DateTime now() => value;
}
@riverpod
Clock clock(Ref ref) => SystemClock();
void main() {
runApp(
ProviderScope(
overrides: [
clockProvider.overrideWith((ref) => FixedClock(DateTime(2026, 1, 1))),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: TimeText())));
}
}
class TimeText extends ConsumerWidget {
const TimeText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final clock = ref.watch(clockProvider);
return Text(clock.now().toIso8601String());
}
}Run dart run build_runner build first so main.g.dart exists. The screen shows 2026-01-01T00:00:00.000, even though clockProvider is declared with SystemClock. Remove the overrides list and the screen shows the current time.
Three details matter here:
- The generated provider is
clockProvider, named after the functionclockplus theProvidersuffix. - The override's return type is
Clock, the same type the original function returns.FixedClockis accepted because it implementsClock. TimeTexthas no idea an override exists. This is the point of the technique.
If you use generator 2.x, the function's ref parameter is the generated ClockRef instead of Ref. The override code is the same either way.
How a lookup reaches an override
A ProviderScope widget owns a ProviderContainer, which is the object that stores provider state. When a widget reads a provider, Riverpod finds the nearest ProviderScope above it. That scope's container checks its override list. If the provider is listed, the override builds the state. Otherwise the request goes to the parent scope, and so on up to the root.
Two consequences follow:
- State is stored per container. If two scopes both override the same provider, each builds and holds its own state. They do not share it.
- A scope that does not override a provider shares that provider's state with its parent. The nested scope is only a different lookup path for that provider.
Choosing the override method
Every provider has overrideWith. Its argument depends on the kind of provider you are replacing.
| Provider kind | Override call | What you pass |
|---|---|---|
| Functional, sync or async (`@riverpod` function) | `fooProvider.overrideWith((ref) => ...)` | A create function that returns the new value or Future |
| Class-based (`@riverpod` class) | `counterProvider.overrideWith(() => FakeCounter())` | A function that returns a notifier instance |
| Family, one argument | `userProvider(1).overrideWith((ref) => ...)` | A create function for that one instance |
| Whole family | `userProvider.overrideWith((ref, id) => ...)` | A create function that also receives the argument |
| Plain `Provider` with a ready value | `fooProvider.overrideWithValue(value)` | The value itself |
The Provider variant overrideWithValue is the shortest form when you already hold the value. Check which overrides your Riverpod version offers on the other provider types, because the available methods have changed between major versions.
Overriding a notifier
A fake notifier must extend the same generated base class as the real one, because the override replaces the whole notifier object. For the Counter from the earlier chapter:
class FakeCounter extends Counter {
@override
int build() => 100;
}
// In the overrides list:
// counterProvider.overrideWith(() => FakeCounter())FakeCounter extends Counter, which itself extends _$Counter. Its build supplies a different initial state, and the inherited increment still works.
Overriding one family instance or all of them
userProvider(1).overrideWith(...) replaces only the instance for id == 1. Reading userProvider(2) still uses the original function. Overriding the family itself replaces every instance, and the create function receives the argument so it can decide what to return.
ProviderScope(
overrides: [
userProvider.overrideWith((ref, id) => User.placeholder(id)),
],
child: const MyApp(),
)Here User.placeholder is an app-defined constructor. Using the whole-family form is usually what you want in widget tests, because you rarely know which ids the screen will request.
Injecting a value created before startup
Some dependencies cannot be created synchronously. SharedPreferences.getInstance() returns a Future, and you do not want every widget handling a loading state for a value that is needed at startup. The usual pattern is a provider that throws by default, plus an override in main once the value exists.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'prefs.g.dart';
@Riverpod(keepAlive: true)
SharedPreferences sharedPreferences(Ref ref) =>
throw UnimplementedError('Override sharedPreferencesProvider in main');
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
runApp(
ProviderScope(
overrides: [
sharedPreferencesProvider.overrideWithValue(prefs),
],
child: const MaterialApp(home: Scaffold()),
),
);
}Add the package with flutter pub add shared_preferences. After this, any provider can call ref.watch(sharedPreferencesProvider) and receive a ready instance, with no AsyncValue handling. The keepAlive: true flag stops the provider from being disposed when nothing listens to it. For an overridden constant this is harmless either way, but it documents that the value lives as long as the app.
The UnimplementedError is a safety net. If a test or a preview forgets to supply the override, the failure message tells you exactly which override is missing.
Overrides and dependent providers
An override changes the provider it names. Providers that depend on it pick up the change automatically, because they read it through ref.watch.
@riverpod
String greeting(Ref ref) {
final now = ref.watch(clockProvider).now();
return now.hour < 12 ? 'Good morning' : 'Good afternoon';
}With the FixedClock override from earlier, greetingProvider is built with the fixed time. You did not override greetingProvider, but its input changed. This is why overriding a low-level dependency is better than overriding many high-level providers: you replace one thing and keep the real logic above it under test.
An override replaces the provider's build step but does not copy its other settings. Auto-dispose and keepAlive behavior come from the original declaration, so check them if a fake's state is disposed earlier than you expect.
Rules and gotchas
- Treat the override list as fixed. Build it once, where the
ProviderScopeis created. Constructing a scope with different overrides on each rebuild leads to rebuilt state or errors. Put changing values behind a provider that other providers watch instead. - Override with the same type. The replacement must produce the type the provider declares. Dart's type system catches most mismatches at compile time.
- Fakes can hide real behavior. A
FixedClocknever advances. A fake repository that never fails never exercises your error UI. Write fakes that can fail on demand. - Overrides are not visible to code outside the scope. A provider read through a different
ProviderContainerdoes not see this scope's overrides. This matters for background code, which must be given the container it should use. - Nested scopes need declared dependencies. If you override a provider in a nested scope so a subtree gets its own value, providers that depend on it must declare that relationship. Otherwise they can keep serving state built from the outer value. The scoped-providers chapter covers the
dependencieslist in full.
Quick checklist
- Does the provider you want to replace exist as a generated
fooProvider? If not, rundart run build_runner build. - Which override method matches its kind: function, notifier, family instance or whole family?
- Does the replacement have the declared type and, for notifiers, extend the generated base class?
- Is the override list built once, at the place where the scope is created?
- If the override is in a nested scope, are the dependent providers declared with
dependencies?
Exercise
A @riverpod function Future<User> user(Ref ref, int id) loads users from a repository. In a widget test the screen shows users with ids 3, 8 and 12, and you want every one of them to return a placeholder user without touching the repository. Which override do you write, and why not userProvider(3).overrideWith(...)?
Show answer
Override the whole family: userProvider.overrideWith((ref, id) => User.placeholder(id)) (with an app-defined placeholder, or any function returning a Future<User> or User as the provider's async type allows). userProvider(3).overrideWith(...) replaces only the instance for id 3, so ids 8 and 12 would still call the real repository. The whole-family form receives the argument, so one function covers every id the screen requests.
Exercise
You define @Riverpod(keepAlive: true) SharedPreferences sharedPreferences(Ref ref) => throw UnimplementedError(); and forget to override it in a widget test. What happens when a widget reads it, and why is this better than returning a default value?
Show answer
Reading the provider throws the UnimplementedError you wrote (surfaced as the provider's error), and the message names the missing override. A silent default would let the test run against wrong data and fail somewhere unrelated, or pass for the wrong reason. Failing at once points straight at the missing override.