Sub topic 9
Singletons, Lazy Singletons, and Factories
Assume you know Dart classes, abstract classes, implements, Future, and basic Flutter state management. This chapter focuses on dependency lifetimes: how long a dependency instance stays available and when a new instance is created.
A dependency can have different lifetimes:
- A singleton uses one instance for the whole application.
- A lazy singleton creates one instance only when it is first requested.
- A factory creates a new instance for every request.
The lifetime should match the dependency's state. A stateless API client can often be shared. A screen-specific view model usually should not be shared globally.
Comparing the lifetimes
| Registration | When the instance is created | How many instances are returned | Typical use |
|---|---|---|---|
| Singleton | During registration | One | App configuration or immutable services |
| Lazy singleton | First lookup | One | API clients, databases, repositories |
| Factory | Every lookup | One per lookup | View models and short-lived controllers |
The difference between a singleton and a lazy singleton is mainly creation timing. Both return the same instance after creation.
flowchart TD
A[Application starts] --> B{Registration type}
B -->|Singleton| C[Create immediately]
B -->|Lazy singleton| D[Wait for first lookup]
B -->|Factory| E[Create on every lookup]
C --> F[Reuse one instance]
D --> F
E --> G[Return a new instance]Singleton and lazy singleton
The get_it package provides registration methods for these lifetimes. The following example defines an abstract repository and registers implementations with different lifetimes.
import 'package:get_it/get_it.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
ApiUserRepository() {
print('ApiUserRepository created');
}
@override
Future<String> fetchName(int id) async => 'User $id';
}
class AppConfig {
const AppConfig(this.apiBaseUrl);
final String apiBaseUrl;
}
final getIt = GetIt.instance;
void setupDependencies() {
getIt.registerSingleton(
const AppConfig('https://api.example.com'),
);
getIt.registerLazySingleton<UserRepository>(
() => ApiUserRepository(),
);
}
Future<void> main() async {
setupDependencies();
final first = getIt<UserRepository>();
final second = getIt<UserRepository>();
print(identical(first, second)); // true
}registerSingleton creates its value while setupDependencies runs. This is useful when creation is cheap and you want configuration errors to appear immediately.
registerLazySingleton stores a function instead. ApiUserRepository is created at the first lookup. Later lookups return that same object. Lazy creation can reduce startup work, but an error may appear later, when the dependency is first used.
A shared instance is safe only when its state can be shared safely. For example, a repository that holds a reusable HTTP client may be a lazy singleton. A view model containing loading state usually should not be one.
Factories for new instances
Use registerFactory when each consumer needs independent state.
class ProfileViewModel {
ProfileViewModel(this.repository);
final UserRepository repository;
String? name;
Future<void> load(int id) async {
name = await repository.fetchName(id);
}
}
void registerViewModels() {
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
}Every call to getIt<ProfileViewModel>() now returns a new view model. Both view models share the repository, but their name fields are separate.
Common lifetime errors
- Registering a mutable view model as a singleton causes unrelated screens to share state.
- Registering an expensive database as a factory opens unnecessary connections.
- Using a lazy singleton for a dependency that must be validated during startup delays failure.
- Forgetting that a singleton can retain user data after logout creates a privacy bug. Clear its state or recreate the dependency when the session changes.
Exercise
Exercise
An AuthSession stores the current user's token, while LoginViewModel stores the state of one login form. Which lifetime should each use, and why?
Show answer
AuthSession can use a scoped or session-wide singleton because screens share the authenticated session. LoginViewModel should use a factory because each login form needs independent, short-lived state.