Skip to content

Instantly share code, notes, and snippets.

@dipendra-sharma
Last active March 13, 2024 10:20
Show Gist options
  • Save dipendra-sharma/fbf8a511d1d2c368ab7b9a474b7e4bd7 to your computer and use it in GitHub Desktop.
Save dipendra-sharma/fbf8a511d1d2c368ab7b9a474b7e4bd7 to your computer and use it in GitHub Desktop.
Discover a streamlined approach to dependency injection with this Dart Service Locator Gist, designed to enhance your Flutter or Dart applications. This robust pattern simplifies dependency management, promoting clean architecture and maintainable code. The ServiceLocator class empowers developers to register dependencies and retrieve service in…
class _ServiceLocator {
final Map<Type, dynamic> _singletons = <Type, dynamic>{};
final Map<Type, Function> _factories = <Type, Function>{};
// Private constructor
_ServiceLocator._();
// Public accessor
static final _ServiceLocator instance = _ServiceLocator._();
// Register a factory function for creating instances
void register<T>(T Function() creator) {
_factories[T] = creator;
}
// Locate a singleton instance
T locate<T>() {
if (_singletons.containsKey(T)) {
return _singletons[T] as T;
} else {
final instance = _createInstance<T>();
_singletons[T] = instance;
return instance;
}
}
T remove<T>() {
return _singletons.remove(T);
}
// Create a new instance every time
T create<T>() {
return _createInstance<T>();
}
clear() {
_singletons.clear();
}
// Helper method to create an instance using the factory function
T _createInstance<T>() {
final factory = _factories[T];
if (factory != null) {
return factory() as T;
} else {
throw Exception('Service not registered in locator: $T');
}
}
}
T singleton<T>() => _ServiceLocator.instance.locate<T>();
T create<T>() => _ServiceLocator.instance.create<T>();
T remove<T>() => _ServiceLocator.instance.remove<T>();
void register<T>(T Function() creator) =>
_ServiceLocator.instance.register(creator);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment