Sub topic 14
Choosing an approach and its trade-offs
This chapter assumes you have read the earlier chapters. You should know constructor injection, abstract classes as dependency contracts, the composition root, and the basics of Provider, get_it, and Riverpod. Here you compare them and decide which to use.
Start from what does not change
Every approach in this tutorial rests on the same two rules:
- A class receives its collaborators. It does not build them.
- One place, the composition root, decides which concrete classes are used.
Provider, get_it, and Riverpod differ in how they store and deliver objects to the classes that need them. They do not change those rules. A ProfileViewModel that takes a UserRepository in its constructor works with all three. This gives you a cheap way to choose, because the cost of switching later is mostly the wiring code, not your business logic.
The sections below describe each option. After that comes a decision procedure and a list of common failure modes.
The options at a glance
Plain constructor injection is also an option. For a small app it is often enough. You build objects in main() and pass them down through constructors.
| Question | Manual constructors | Provider | get_it | Riverpod |
|---|---|---|---|---|
| Where dependencies live | Local variables and fields | Widget tree | Global registry object | A container, usually under `ProviderScope` |
| Needs `BuildContext` to read | No | Yes (`context.read`) | No | No in providers, `ref` in widgets |
| Missing dependency shows up | Compile time | Runtime, when the widget builds | Runtime, on first lookup | Mostly compile time, since providers are variables |
| Natural scoping | By hand | Subtree of the widget tree | Manual (scopes, or register and unregister) | Overrides, and `autoDispose` for lifetime |
| Test replacement | Pass a fake | Wrap with a provider holding the fake | Register a fake, reset after the test | `overrides` on the container |
| Extra learning cost | None | Low | Low | Medium |
The table compares tendencies, not rules. You can build a fully compile-safe app with Provider if you are disciplined, and you can misuse Riverpod. Read it as the default behavior of each tool.
Trade-offs of each approach
Manual constructor injection
You get the best compile-time safety and no dependencies on third-party packages. The cost is plumbing. If a deeply nested widget needs a repository, every widget between it and the root must pass the repository along. That "prop drilling" is the reason the other approaches exist.
Use manual injection when the object graph is small, or inside a single feature where only two or three objects are wired.
Provider
Provider uses InheritedWidget underneath, so dependencies follow the widget tree. This gives you scoping for free. A provider placed above a route is available to that route and its children, and it is disposed when the route leaves the tree.
The costs:
- Reading requires a
BuildContextbelow the provider. Code outside the tree, such as a background service or a push notification handler, cannot reach the dependency. - A missing provider is a runtime
ProviderNotFoundException. It is thrown when the widget builds, not when you compile. - The type you read must match the type you registered. If you register
Provider<ApiUserRepository>and readcontext.read<UserRepository>(), the lookup fails. Always give the abstract type as the type argument.
get_it
get_it is a service locator. Any code can call getIt<UserRepository>(), with no context. That makes it easy to use from non-widget code and keeps widgets free of provider wrappers.
The costs:
- Dependencies become hidden. If a class calls
getIt<...>()inside its methods, its constructor no longer shows what it needs. Prefer to callgetItonly in the composition root and registration closures, and pass results through constructors, as the earlier get_it example does. - A missing registration fails at runtime with an error naming the unregistered type. It fails on the first lookup, which may be a screen the user reaches late.
- The registry is global state. Tests that register fakes leave them behind unless you reset.
- There is no tie to the widget tree, so scoping is your job.
Riverpod
Riverpod providers are top-level variables, so reading one is a normal Dart reference, and a typo is a compile error. The container holds state, which lets you override any provider in tests or in a subtree. Dependencies between providers are declared with ref.watch, so the graph is explicit and Riverpod can rebuild or dispose parts of it for you.
The costs:
- It is a larger concept set: provider kinds,
ref,autoDispose, families. - It ties your code to Riverpod. Provider and get_it can be used as a thin delivery layer, but Riverpod providers often also carry your state management.
- Code generation (
riverpod_generator) is optional but common, and adds a build step.
A decision procedure
Work through these questions in order. Stop at the first that fits.
Treat the diagram as a starting point. These factors can override it:
- Existing code. Consistency usually beats theoretical fit. A codebase that already uses Provider for view models gains little from adding a second container.
- Team familiarity. A pattern the whole team understands beats a better pattern that two people understand.
- Testing needs. If you want to override dependencies in widget tests without touching production code, Provider and Riverpod both do this directly in the tree. get_it works too but needs reset discipline.
- Scoping needs. If a dependency must live only while a feature or login session is active, tree-based approaches give you that naturally. With get_it you must register and unregister at the right moments.
- Compile-time safety. If you have been bitten by runtime lookup failures, favor Riverpod or manual injection.
Combining approaches
Mixing is common and legitimate. A typical combination is get_it for long-lived services (database, HTTP client, analytics) and Provider for view models, which are tied to screens. Keep the combination readable by making the bridge explicit:
import 'package:flutter/widgets.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}
final getIt = GetIt.instance;
void main() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
runApp(
ChangeNotifierProvider<ProfileViewModel>(
create: (_) => ProfileViewModel(getIt<UserRepository>()),
child: const SizedBox(),
),
);
}The service comes from getit, but ProfileViewModel still takes it in its constructor. The view model does not know getit exists. That is the property to protect in any mix: only the composition root touches the container.
Common failure modes
- Registering the concrete type, requesting the abstract one. With Provider,
Provider<ApiUserRepository>does not satisfycontext.read<UserRepository>(). With get_it,registerLazySingleton(() => ApiUserRepository())registersApiUserRepository, notUserRepository. Supply the type argument explicitly. - Wrong lifetime. Registering a view model as a singleton keeps the old screen's state when the user returns to the screen. Registering an expensive client as a factory creates a new connection for every lookup. Match the lifetime to the object: services are usually singletons, per-screen state is a factory or a provider scoped to the route.
- Reading before registering. In get_it, a lookup that runs before
setupLocator()fails. Call setup first inmain(), beforerunApp. - Using
context.readinbuildto listen.readdoes not rebuild the widget. Usewatchwhen the UI should update, andreadin callbacks and increate. - Leaked fakes between tests. A get_it registration made in one test is still there in the next. Reset in
tearDown, as shown next.
The following test setup keeps get_it tests isolated:
import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
class ProfileViewModel {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
}
}
void main() {
final getIt = GetIt.instance;
setUp(() {
getIt.registerLazySingleton<UserRepository>(() => FakeUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
});
tearDown(() async {
await getIt.reset();
});
test('view model gets the fake from the locator', () async {
final viewModel = getIt<ProfileViewModel>();
await viewModel.load(1);
expect(viewModel.name, 'Test User');
});
}Migrating later
Because your classes take dependencies through constructors, a migration changes only the composition root. To move from get_it to Provider, replace each registerLazySingleton with a Provider entry in MultiProvider, and replace each getIt<T>() in the root with context.read<T>(). The view models do not change. If a migration requires editing your view models or repositories, that is a sign that they were reaching into the container directly.
Exercise
A team's app has a PushService that must read the current user's repository when a notification arrives while no screen is visible. The app uses Provider for all view models. Which delivery mechanism fits the notification code, and how should the view models still receive the repository?
Show answer
The notification handler runs outside the widget tree, so it has no BuildContext to call context.read with. A service locator such as getit fits it, with the repository registered as a lazy singleton. The view models should still receive the repository through their constructors. The composition root passes getIt<UserRepository>() into ChangeNotifierProvider's create. Only the root touches getit, so the view models stay testable without it.
Exercise
A test registers FakeUserRepository in get_it and passes. The next test, which expects the real ApiUserRepository, unexpectedly gets the fake. What is the cause and the fix?
Show answer
get_it is a global registry, so the first test's registration remains. The fix is to call await getIt.reset() in tearDown so that each test starts with an empty registry and registers what it needs.
Exercise
You register Provider<ApiUserRepository> and a widget calls context.read<UserRepository>(). What happens and why?
Show answer
A ProviderNotFoundException is thrown at runtime. Provider looks up by the exact type argument, and no provider of type UserRepository exists above the widget. Register it as Provider<UserRepository>(create: (_) => ApiUserRepository()).