Sub topic 9
Singletons, lazy singletons, and factories
This chapter covers how long a dependency lives and how many copies of it exist. It assumes you know constructor injection, the composition root idea, and the basics of Provider and get_it from the earlier chapters. It also assumes you can read Dart Future code and know what ChangeNotifier does.
Why lifetime is a design decision
Every registered dependency answers two questions: when is it created, and does each consumer get the same object or a new one? The answers are the dependency's lifetime. A wrong choice rarely fails at compile time. It shows up as a shopping cart that empties itself, two screens that disagree about the logged-in user, or an HTTP client rebuilt on every request.
There are three lifetimes you will use most often:
- Singleton: one instance, created when you register it.
- Lazy singleton: one instance, created the first time something asks for it.
- Factory: a new instance on every request.
The three lifetimes in get_it
get_it names each lifetime directly. The example below shows all three and prints when each object is created.
import 'package:get_it/get_it.dart';
class Logger {
Logger() {
print('Logger created');
}
}
class ApiClient {
ApiClient(this.logger) {
print('ApiClient created');
}
final Logger logger;
}
class CartViewModel {
CartViewModel(this.client) {
print('CartViewModel created');
}
final ApiClient client;
}
final getIt = GetIt.instance;
void main() {
// Singleton: the instance already exists when you register it.
getIt.registerSingleton<Logger>(Logger());
// Lazy singleton: the closure runs on the first request only.
getIt.registerLazySingleton<ApiClient>(() => ApiClient(getIt<Logger>()));
// Factory: the closure runs on every request.
getIt.registerFactory<CartViewModel>(() => CartViewModel(getIt<ApiClient>()));
print('registration finished');
final a = getIt<CartViewModel>();
final b = getIt<CartViewModel>();
print(identical(a, b)); // false
print(identical(a.client, b.client)); // true
}The output is:
Logger created
registration finished
ApiClient created
CartViewModel created
CartViewModel created
false
trueLogger is built before registration finishes because you passed an existing object. ApiClient is built only when the first CartViewModel needs it. The second CartViewModel reuses the same ApiClient but is itself a new object.
Comparing the lifetimes
| Lifetime | get_it call | Created | Instances | Typical use |
|---|---|---|---|---|
| Singleton | `registerSingleton` | At registration | One | Logger, config, objects needed at startup |
| Lazy singleton | `registerLazySingleton` | On first request | One | Repositories, API clients, databases |
| Factory | `registerFactory` | On every request | Many | View models for a screen, form state |
When to use each
Use a singleton when the object must exist before anything else runs, or when its constructor has side effects you want at a known moment. Examples are a crash reporter, or a configuration object read from a file before runApp.
Use a lazy singleton as your default for stateless or shared services. A repository that wraps an HTTP client holds no per-screen state, so one instance is enough. Laziness also keeps startup fast: a service for a screen the user never opens is never built.
Use a factory for anything that holds state belonging to one screen or one task. A ProfileViewModel stores the loaded name. If you registered it as a singleton, a second profile screen would show the first screen's data.
A common rule: shared and stateless means singleton, owned by one screen and stateful means factory.
Lifetimes in Provider
Provider has the same ideas, expressed through widgets instead of registration calls. The widget's position in the tree determines its lifetime.
import 'package:flutter/material.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();
}
}
void main() {
runApp(
MultiProvider(
providers: [
// Lives as long as this widget stays in the tree.
Provider<UserRepository>(create: (_) => ApiUserRepository()),
],
child: const MaterialApp(home: ProfilePage()),
),
);
}
class ProfilePage extends StatelessWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context) {
// A new view model is created when this page enters the tree
// and disposed when it leaves.
return ChangeNotifierProvider<ProfileViewModel>(
create: (context) => ProfileViewModel(context.read<UserRepository>())..load(1),
child: Consumer<ProfileViewModel>(
builder: (context, viewModel, _) =>
Text(viewModel.name ?? 'Loading...'),
),
);
}
}The repository provider sits above MaterialApp, so it behaves like an app-wide singleton. The view model provider sits inside the page, so each time the page is pushed you get a fresh view model, which behaves like a factory.
Three Provider details affect lifetime:
createis lazy by default. The object is built the first time a widget reads it, not when the provider is inserted. Passlazy: falseto build it immediately.- A provider built with
createdisposes its value when it leaves the tree.ChangeNotifierProvidercallsdispose()on the notifier. For plainProvider, pass adisposecallback if the object needs cleanup. Provider.valueandChangeNotifierProvider.valuenever dispose the object, because they assume someone else owns it. Do not create a new object inside.valuein abuildmethod, or you will get a new instance on every rebuild.
Common errors
Registering a stateful object as a singleton. The symptom is state leaking between screens. Fix it by switching to registerFactory.
Registering the same type twice. get_it throws an assertion error when a type is already registered. This is deliberate, because a silent overwrite hides wiring mistakes. In tests, either call getIt.reset() in setUp or tearDown, or set getIt.allowReassignment = true if you really want replacement.
Resolving before registering. A call to getIt<UserRepository>() before setupLocator() runs throws. Call setup first in main, before runApp.
Holding a factory product too long. A factory gives you a new object, but nothing disposes it for you. If the view model owns a stream subscription, a widget's dispose must release it. get_it does not track objects created by factories.
Captured stale singletons. A singleton that stores a reference to a factory product keeps that product alive forever. Do not inject a screen's view model into a singleton service. Dependencies should point from short-lived objects toward long-lived ones, not the other way.
Lazy does not mean free
Lazy creation moves the cost of construction to the first use. If a lazy singleton opens a database, the first screen that needs it pays that delay, and a failure happens in the middle of a user action instead of at startup. For work that must succeed before the UI appears, use an explicit startup step. get_it supports this with registerSingletonAsync, which accepts an async factory, together with await getIt.allReady() before runApp.
import 'package:flutter/widgets.dart';
import 'package:get_it/get_it.dart';
class Database {
static Future<Database> open() async {
// Open files, run migrations, and so on.
return Database();
}
}
final getIt = GetIt.instance;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
getIt.registerSingletonAsync<Database>(() => Database.open());
await getIt.allReady();
runApp(const Placeholder());
}After allReady() completes, getIt<Database>() returns the opened database synchronously.
Factories with parameters
Sometimes a factory needs a runtime value, such as the id of the user being shown. Constructor arguments cannot come from the registration, so get_it offers registerFactoryParam. It takes up to two parameters.
import 'package:get_it/get_it.dart';
class UserDetailViewModel {
UserDetailViewModel(this.userId);
final int userId;
}
final getIt = GetIt.instance;
void main() {
getIt.registerFactoryParam<UserDetailViewModel, int, void>(
(userId, _) => UserDetailViewModel(userId),
);
final viewModel = getIt<UserDetailViewModel>(param1: 42);
print(viewModel.userId); // 42
}The parameter types are not checked at compile time against the call site. If you forget param1, you get a runtime error. For that reason many teams prefer to resolve a plain factory and pass the id into a load(id) method, as ProfileViewModel does.
Disposing singletons
Singletons that own resources, such as streams or open connections, need a cleanup path. get_it accepts a dispose callback at registration time, and it runs when you unregister the type or reset the container.
import 'package:get_it/get_it.dart';
class EventBus {
void close() => print('EventBus closed');
}
final getIt = GetIt.instance;
Future<void> main() async {
getIt.registerLazySingleton<EventBus>(
() => EventBus(),
dispose: (bus) => bus.close(),
);
getIt<EventBus>(); // Forces creation.
await getIt.reset(); // Prints: EventBus closed
}A lazy singleton that was never requested is never created, so its dispose callback does not run.
Choosing a lifetime: a checklist
- Does the object hold data tied to one screen, one form, or one request? Use a factory, or a provider placed inside that screen.
- Is it shared, and does it need no setup before the UI appears? Use a lazy singleton.
- Must it exist, or fail loudly, before
runApp? Register it eagerly, or useregisterSingletonAsyncwithallReady(). - Does it own a resource? Add a dispose callback, or rely on the provider that disposes it.
- Does anything long-lived depend on it? If so, it should probably not be a factory product.
Exercise
A CartViewModel stores the items a user added on the cart screen. A teammate registers it with registerLazySingleton. After the user leaves the cart screen and opens it again, the old items still appear. What is the cause, and what is the fix?
Show answer
A lazy singleton creates one instance on the first request and returns that same instance afterward, so the state survives across visits. Register the view model with registerFactory so each request creates a new CartViewModel, and keep the shared CartRepository as a lazy singleton. If you want the cart to persist deliberately, store the items in a repository rather than in the view model.
Exercise
What does this code print, and in what order?
final getIt = GetIt.instance;
getIt.registerLazySingleton<Logger>(() => Logger());
print('registered');
getIt<Logger>();
getIt<Logger>();
Assume the Logger constructor prints Logger created.
Show answer
It prints registered, then Logger created once. The closure runs on the first getIt<Logger>() call. The second call returns the stored instance without running the closure.
Exercise
In Provider, why is ChangeNotifierProvider.value(value: ProfileViewModel(repo)) inside a build method a bug, and what should you use instead?
Show answer
Each rebuild of the parent creates a new ProfileViewModel, so the state is lost. The .value constructor also never disposes the notifier. Use ChangeNotifierProvider(create: (_) => ProfileViewModel(repo)), which creates the object once for the provider's lifetime and disposes it when the provider leaves the tree.