Toggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage
Factory singleton
• Section: Dart
registerFactory v registerSingleton
registerFactory
Creates new instance each time: Every call to getIt.get<T>() executes the factory function and returns a new instance
Registration by function: You register a factory function that creates the instance
No instance tracking: GetIt doesn’t keep track of individual instances created by the factory
Cannot unregister by instance: Since GetIt doesn’t track instances, you can’t use unregister(instance: someInstance)
// Register a factory function
getIt.registerFactory<EntryPoint>(()=>EntryPoint(child:someWidget));// Each call creates a NEW instance
finalentry1=getIt.get<EntryPoint>();// New instance
finalentry2=getIt.get<EntryPoint>();// Different new instance
print(entry1==entry2);// false - different objects
// This FAILS because GetIt doesn't track factory instances
getIt.unregister<EntryPoint>(instance:entry1);// ❌ Error!
registerSingleton
Single instance: Only one instance exists, created at registration time or first access
Registration by instance: You register an actual instance object
Instance tracking: GetIt keeps a reference to the single instance
Can unregister by instance: Since there’s only one tracked instance, you can unregister it
// Register an actual instance
finalentryPoint=EntryPoint(child:someWidget);getIt.registerSingleton<EntryPoint>(entryPoint);// Both calls return the SAME instance
finalentry1=getIt.get<EntryPoint>();// Same instance
finalentry2=getIt.get<EntryPoint>();// Same instance
print(entry1==entry2);// true - same object
// This WORKS because GetIt tracks the singleton instance
getIt.unregister<EntryPoint>(instance:entry1);// ✅ Success!
Unregistering GetIt Services
Factory Unregistration
// Register factory
getIt.registerFactory<EntryPoint>(()=>EntryPoint(child:someWidget));// Unregister by TYPE only (no instance)
getIt.unregister<EntryPoint>();// ✅ Works!
// This FAILS - factories can't be unregistered by instance
getIt.unregister<EntryPoint>(instance:someInstance);// ❌ Error!
Singleton Unregistration
// Register singleton
finalentryPoint=EntryPoint(child:someWidget);getIt.registerSingleton<EntryPoint>(entryPoint);// Option 1: Unregister by type
getIt.unregister<EntryPoint>();// ✅ Works!
// Option 2: Unregister by instance
getIt.unregister<EntryPoint>(instance:entryPoint);// ✅ Also works!