Sub topic 9
Overriding Providers with ProviderScope
This chapter assumes you know Dart futures, Flutter widgets, ProviderScope, ConsumerWidget, and ref.watch. It also assumes that riverpod_generator has created the .g.dart files for your annotated providers.
An override replaces how a provider is built for one part of the widget tree. This lets the same screen use a real repository in production and a fake repository in a test or preview.
How a ProviderScope override works
A ProviderScope owns a Riverpod container. The overrides list changes provider behavior inside that container and all of its descendants.
Suppose a user provider depends on a repository provider:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'user_providers.g.dart';
class User {
const User({required this.id, required this.name});
final int id;
final String name;
}
abstract interface class UserRepository {
Future<User> fetchUser(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<User> fetchUser(int id) {
throw UnimplementedError('Connect this class to your API');
}
}
class FakeUserRepository implements UserRepository {
@override
Future<User> fetchUser(int id) async {
return User(id: id, name: 'Test user $id');
}
}
@riverpod
UserRepository userRepository(Ref ref) {
return ApiUserRepository();
}
@riverpod
Future<User> user(Ref ref, int id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
}After generation, userRepositoryProvider and the family userProvider(id) are available. The application can replace only the repository:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'user_providers.dart';
void main() {
runApp(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWith(
(ref) => FakeUserRepository(),
),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: UserScreen());
}
}
class UserScreen extends ConsumerWidget {
const UserScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncUser = ref.watch(userProvider(42));
return Scaffold(
body: Center(
child: asyncUser.when(
data: (user) => Text(user.name),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
),
),
);
}
}UserScreen still watches userProvider(42). Riverpod builds that provider normally, but when the provider asks for userRepositoryProvider, the scoped override supplies FakeUserRepository.
Choosing what to override
Override the provider at the boundary where the environment changes. Replacing a repository is usually better than replacing every provider that uses it. The application logic remains the same, while the data source changes.
Common uses include:
- Supplying a fake API for tests.
- Providing preview data in a Flutter widget preview.
- Selecting a different configuration for a feature subtree.
- Replacing platform services on desktop or web.
- Injecting a logged-in user into a part of the application.
overrideWith receives a builder. The builder can use ref to read other providers in the new scope:
ProviderScope(
overrides: [
userRepositoryProvider.overrideWith(
(ref) => CachedUserRepository(
source: ref.watch(apiClientProvider),
),
),
],
child: const UserScreen(),
)Use overrideWithValue when you already have an object and do not need a builder:
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
child: const UserScreen(),
)The exact override must match the provider being replaced. An override on userProvider(42) does not replace userProvider(7), because family arguments identify separate provider instances.
Nested scopes and boundaries
A nested ProviderScope can override a provider for only one subtree:
Column(
children: [
const ProductionUserPanel(),
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
child: const PreviewUserPanel(),
),
],
)ProductionUserPanel uses the nearest parent behavior. PreviewUserPanel uses the fake repository. Widgets outside the nested scope are unaffected.
A scope does not change providers for widgets above it. Place the scope around the smallest subtree that needs the replacement. This keeps the override easy to understand and prevents unrelated screens from receiving test or preview data.
Common mistakes
- Forgetting to run
dart run build_runner buildleaves provider names unavailable or stale. - Creating an override but placing the
ProviderScopebeside, rather than around, the widget that reads the provider means the widget cannot see the override. - Overriding a dependency that the target provider does not actually watch has no effect.
- Reusing a mutable fake across unrelated scopes can leak state. Create a separate fake when each scope needs independent state.
Exercise
A screen watches userProvider(42), and userProvider reads userRepositoryProvider. Where should you place a fake repository override if only that screen should use it?
Show answer
Wrap the screen in a ProviderScope whose overrides list contains userRepositoryProvider.overrideWithValue(fakeRepository). The screen and its descendants will use the fake, while widgets outside that scope will not.