Sub topic 14
Choosing a Dependency Injection Approach in Flutter
Assume you know Dart classes, abstract classes, implements, Future, async and await, Flutter's widget tree, BuildContext, and basic ChangeNotifier state management.
Dependency injection (DI) means giving a class the objects it needs instead of making those objects itself. Flutter apps commonly use Provider, get_it, or Riverpod to supply dependencies. These tools solve similar problems, but they make different trade-offs.
Start with constructor injection
Keep the core class independent of the DI tool. Depend on an abstract class and accept it through the constructor:
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ProfileViewModel {
ProfileViewModel(this.repository);
final UserRepository repository;
Future<String> loadName(int id) {
return repository.fetchName(id);
}
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
return 'User $id';
}
}
void main() async {
final viewModel = ProfileViewModel(ApiUserRepository());
print(await viewModel.loadName(7));
}This design works with any DI approach. It also makes unit tests simple because a fake repository can be passed directly.
Compare the main approaches
| Approach | Strength | Cost |
|---|---|---|
| Provider | Clear widget-tree ownership and lifetimes | Requires `BuildContext` at lookup points |
| `get_it` | Simple global registration and lookup | Dependencies can become hidden |
| Riverpod | Strong overrides, scopes, and reactive composition | Adds concepts and provider-specific APIs |
| Manual wiring | Maximum clarity and fewest dependencies | More setup code in larger applications |
Provider: dependencies follow the widget tree
Provider builds on Flutter's inherited-widget mechanism. A provider stores an object above a subtree, and descendants read it through BuildContext.
Use Provider when a dependency belongs naturally to a screen, feature, or application subtree. It makes ownership visible in the widget tree and supports disposal through provider lifetimes.
Its main cost is that lookup often requires a context. Moving logic away from widgets can require passing dependencies or context carefully. Do not call Provider.of deep inside domain code. Keep context-based lookup near the composition root.
`get_it`: a service locator
get_it stores registrations in a central locator:
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);A lazy singleton is created on first lookup. A factory creates a new object for every lookup. A regular singleton is created when it is registered.
get_it is useful when many non-widget classes need shared services. It avoids passing BuildContext, but lookup hides a class's dependencies. A constructor that calls getIt is harder to understand and test than one that receives its dependencies directly. Prefer resolving objects at the composition root, then passing them into constructors.
Riverpod: providers as a dependency graph
Riverpod represents dependencies as providers. Providers can depend on other providers, react to changes, and be overridden in tests. It also supports scopes that replace dependencies for part of the application.
Riverpod fits applications already using Riverpod for state management. It gives strong testing and scoping tools, but developers must learn provider lifecycles, ref, watching, reading, and asynchronous states.
Scopes, code generation, and trade-offs
A scope limits a dependency's lifetime and visibility. Use a feature scope for a feature-specific repository, or a session scope for objects that exist only while a user is signed in. Avoid making every object a global singleton. Shared mutable state can leak between tests and user sessions.
The injectable package can generate get_it registrations from annotations. It reduces repetitive wiring in large applications, but generated code adds build steps and another layer to debug. Introduce it after manual registrations become difficult to maintain.
Choose the simplest approach that makes ownership, lifetime, and testing clear:
- Use manual wiring for small applications.
- Use Provider when dependencies follow widget subtrees.
- Use
get_itfor centrally managed services, while keeping constructor injection. - Use Riverpod when reactive state, overrides, and scoping are central requirements.
Exercise
A repository is needed by several screens, but tests must replace it easily. Which design should you use?
Show answer
Define an abstract repository, inject it through constructors, and choose Provider, get_it, or Riverpod only to create and supply the concrete implementation at the composition root.