Back to results for “Flutter Performance Optimization”
Flutter › Dependency Injection in Flutter (GetIt & Service Locator)

What is the difference between registerSingleton, registerLazySingleton, and registerFactory when registering a dependency with GetIt?

Intermediate

Answer

registerSingleton immediately creates and registers exactly one single shared instance of a given dependency right away at the moment of registration, registerLazySingleton instead defers actually creating that single shared instance until the very first time it is genuinely requested, which can improve your app's startup performance for a dependency that might not actually be needed immediately, and registerFactory creates and returns a brand new, completely separate instance every single time that dependency is actually requested, which is appropriate for objects that should genuinely never be shared or reused between different requests.
getIt.registerLazySingleton<DatabaseService>(() => DatabaseService());
getIt.registerFactory<OrderFormViewModel>(() => OrderFormViewModel());
Real-world example An app registers its DatabaseService as a lazy singleton since it involves a somewhat expensive initialization process that should only actually happen the first time it is genuinely needed, while registering its OrderFormViewModel as a factory since a brand new fresh instance is required every single time a user opens the order form screen.

Common follow-ups: When would you specifically choose registerSingleton over registerLazySingleton?;How do you properly reset or unregister a specific dependency when using GetIt, such as during testing?