Sub topic 7
The Service Locator Pattern
Prerequisites
This chapter assumes you understand Dart classes, abstract classes, constructors, Future, and basic Flutter state management. You should also know that a dependency is an object another object needs to do its work.
What a Service Locator Does
A service locator is a central object that stores dependencies and returns them when code asks for them. Instead of passing a repository through several constructors, a class looks it up from the locator.
The locator usually maps an abstract type to an object:
UserRepository → ApiUserRepositoryA class can then request UserRepository without knowing how the object was created.
A locator is different from constructor injection. With constructor injection, the dependency appears in the constructor:
ProfileViewModel(this._repository);With a locator, the class retrieves the dependency internally:
class ProfileViewModel extends ChangeNotifier {
final UserRepository _repository =
ServiceLocator.instance.get<UserRepository>();
}The second version has a simpler constructor, but its dependency is less visible. Someone reading the constructor might not realize that ProfileViewModel requires a UserRepository.
A Small Service Locator
The following example uses a hand-written locator. It is complete Dart code and demonstrates the core pattern without a package:
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}
class ServiceLocator {
ServiceLocator._();
static final instance = ServiceLocator._();
final Map<Type, Object> _services = {};
void register<T extends Object>(T service) {
_services[T] = service;
}
T get<T extends Object>() {
final service = _services[T];
if (service is T) {
return service;
}
throw StateError('No service registered for $T');
}
}
class ProfileViewModel {
UserRepository get _repository =>
ServiceLocator.instance.get<UserRepository>();
Future<String> loadName(int id) {
return _repository.fetchName(id);
}
}
void main() async {
ServiceLocator.instance.register<UserRepository>(
ApiUserRepository(),
);
final viewModel = ProfileViewModel();
print(await viewModel.loadName(1));
}The Map<Type, Object> stores one object for each registered type. Startup code registers the concrete implementation. Later, ProfileViewModel asks for the abstract UserRepository type.
Packages such as get_it provide a more complete locator with factories, lazy creation, disposal, and scopes. The underlying idea is the same: register services at startup and resolve them where they are needed.
Benefits and Costs
A service locator can be useful when many parts of an application need shared services. It can reduce constructor plumbing and keep object creation in one startup area. It also supports different implementations for development, production, and tests.
However, lookups hide dependencies. A missing registration causes a runtime error instead of a compile-time error. A class also becomes coupled to the locator itself, which can make unit tests and reuse harder.
Use a locator carefully:
- Register dependencies before
runApp. - Keep registrations in one composition-root function.
- Depend on abstract types, not concrete classes.
- Avoid calling the locator throughout business logic when constructor injection is simple.
- Reset or replace registrations between tests.
Choosing the Pattern
Constructor injection is usually clearer for view models and domain classes. A service locator can be convenient for application-wide services such as logging, configuration, or storage. Many Flutter projects use both: explicit constructors for core logic and a locator at the application boundary.
Exercise
What is the main cost of retrieving a repository from a service locator instead of receiving it through a constructor?
Show answer
The dependency becomes hidden inside the class, so missing registrations fail at runtime and unit tests must configure the locator or provide a replacement.