Dependency Injection with get_it and injectable
Register and resolve dependencies using get_it service locators and injectable code generation.
Why a Service Locator?
In a clean, modular Flutter app you want your presentation layer to depend on abstractions, not on the concrete classes that build them. Manually constructing objects (RemoteApi(HttpClient(...))) everywhere leaks construction details and makes testing painful.
A service locator centralizes object creation and lookup. get_it is the de-facto service locator for Dart/Flutter: you register how to build a type once, then resolve it anywhere with a single call.
- Decoupling — widgets ask for an interface, not a constructor.
- Testability — swap a real implementation for a fake in tests.
- Lifecycle control — singleton vs. fresh instance per request.
The GetIt Instance
GetIt exposes a global singleton via GetIt.instance (commonly aliased getIt or sl). You can also create isolated instances with GetIt.asNewInstance() for tests.
The plain Dart API mirrors what code generation will produce later, so it pays to understand it first. Below is the locator pattern modeled with plain classes — no Flutter needed.
// A tiny hand-rolled service locator to show the idea.
class Locator {
final _factories = <Type, Object Function()>{};
final _singletons = <Type, Object>{};
void registerFactory<T>(T Function() create) =>
_factories[T] = () => create() as Object;
void registerSingleton<T>(T instance) =>
_singletons[T] = instance as Object;
T get<T>() {
if (_singletons.containsKey(T)) return _singletons[T] as T;
final f = _factories[T];
if (f == null) throw StateError('No registration for $T');
return f() as T;
}
}
class ApiClient {
final String baseUrl;
ApiClient(this.baseUrl);
}
void main() {
final sl = Locator();
sl.registerSingleton<ApiClient>(ApiClient('https://api.example.com'));
final api = sl.get<ApiClient>();
print('Resolved ApiClient -> ${api.baseUrl}');
}All lessons in this course
- Domain, Data, and Presentation Layer Boundaries
- Dependency Injection with get_it and injectable
- Feature-First Folder Structure and Melos Monorepos
- Either, Failure Types, and Functional Error Handling