Sub topic 3
Singletons, Lazy Singletons, and Factories
This chapter assumes you know abstract classes, constructor injection, ChangeNotifier, and basic Riverpod providers. It covers how long dependencies live, how to test them, and how to pick a tool.
Lifetimes in get_it
A lifetime is how long an object stays alive once it is created. get_it supports three lifetimes:
- Singleton: created at registration and shared for the whole app.
- Lazy singleton: created on first request, then shared.
- Factory: a new instance on every request.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}
class ProfileViewModel {
ProfileViewModel(this.repository);
final UserRepository repository;
}
final getIt = GetIt.instance;
void setupLocator() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
}Testing with fakes and overrides
A fake is a hand-written class that replaces a real dependency. Because ProfileViewModel depends on the abstract UserRepository, a fake can be passed in directly:
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}In Riverpod, an override swaps a provider's value inside a ProviderContainer:
final userRepositoryProvider = Provider<UserRepository>(
(ref) => ApiUserRepository(),
);
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);Dependency injection with Riverpod
Riverpod providers are declared at top level. Other providers read them with ref.watch, so the wiring lives in the provider graph rather than in a widget tree. Overrides, shown above, replace any provider without changing the code that reads it.
Scoping dependencies
A scope limits how long a dependency lives. In get_it, pushNewScope() starts a temporary set of registrations, and popScope() discards them, which suits a user session or a feature flow. In Riverpod, a ProviderScope placed lower in the widget tree creates providers that exist only in that subtree.
Generating registrations with injectable
The injectable package generates getit registration code from annotations. Annotate a class with @lazySingleton, @injectable, or @singleton, then run `dart run buildrunner build. The generated code replaces hand-written register` calls.
Choosing an approach
flowchart TD
A[First request for a dependency] --> B{Registered as?}
B -->|Singleton| C[Reuse instance created at startup]
B -->|Lazy singleton| D[Create once, then reuse]
B -->|Factory| E[Create a new instance each time]caption: How get_it chooses between lifetimes when a dependency is requested.
alt: A flowchart showing that a singleton is reused from startup, a lazy singleton is created once on first request, and a factory creates a new instance on every request.
| Approach | Strength | Trade-off |
|---|---|---|
| Provider | Built into the widget tree, simple | Tied to `BuildContext` |
| get_it | Works outside widgets, explicit lifetimes | Manual registration, no compile-time checks |
| Riverpod | Compile-safe, easy overrides in tests | Extra concepts to learn |
> Note: Use a singleton only for stateless or shared services. Shared mutable state hides bugs that appear only when instances are reused.
Exercise
Exercise
A ProfileViewModel holds form input for one screen and should start empty each time the screen opens. Which get_it lifetime should you use, and why?
Show answer
Use registerFactory, because each request must return a new instance with its own state. A singleton or lazy singleton would share the old input between screens.