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
final entry1 = getIt.get<EntryPoint>(); // New instance
final entry2 = 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
final entryPoint = EntryPoint(child: someWidget);
getIt.registerSingleton<EntryPoint>(entryPoint);

// Both calls return the SAME instance
final entry1 = getIt.get<EntryPoint>(); // Same instance
final entry2 = 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
final entryPoint = 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!