Sub topic 13
Generating registrations with injectable
This chapter covers injectable, a code generator that writes your get_it registration code from annotations. It assumes you know how get_it registers and resolves objects, how singleton, lazy singleton, and factory lifetimes differ, and how constructor injection works. It also assumes you can run dart run commands in a Flutter project.
The problem injectable solves
In the get_it chapter you wrote a setupLocator() function by hand:
void setupLocator() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
}This works, but each new class needs a matching line. Each constructor change also means editing the registration that calls it. If you forget to update one, the compiler may not catch it, because getIt<T>() fails at runtime when a type is missing. In a large app this list becomes long and easy to get wrong.
injectable moves that information onto the classes. You annotate a class with its lifetime, and a build step reads every constructor and writes the setupLocator() equivalent for you. It still uses get_it underneath, so resolving a dependency with getIt<T>() works exactly as before.
Setup
Add the runtime packages and the build tools:
dependencies:
get_it: ^7.6.0
injectable: ^2.3.0
dev_dependencies:
build_runner: ^2.4.0
injectable_generator: ^2.4.0Check pub.dev for current version numbers. Then create lib/injection.dart:
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'injection.config.dart';
final getIt = GetIt.instance;
@InjectableInit()
void configureDependencies(String environment) =>
getIt.init(environment: environment);@InjectableInit() tells the generator to write injection.config.dart next to this file. That file defines the init extension method on GetIt. The import fails until you run the generator for the first time.
Annotating classes
The annotations map directly to the lifetimes you already know.
| Annotation | Equivalent get_it call | Lifetime |
|---|---|---|
| `@injectable` | `registerFactory` | New instance on every request |
| `@singleton` | `registerSingleton` | Created when `init` runs |
| `@lazySingleton` | `registerLazySingleton` | Created on first request, then shared |
Here is the repository and view model from earlier chapters, annotated:
import 'package:flutter/foundation.dart';
import 'package:injectable/injectable.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
@LazySingleton(as: UserRepository)
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
// Call the real backend here.
return 'User $id';
}
}
@injectable
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}The as: UserRepository argument registers the class under its abstract type. Without it, the generator would register ApiUserRepository itself, and ProfileViewModel could not be built because it asks for UserRepository. This is the most common first mistake.
Running the generator
Run this from the project root:
dart run build_runner build --delete-conflicting-outputsDuring development, use watch instead of build so the file is regenerated on every save:
dart run build_runner watch --delete-conflicting-outputsThe generated injection.config.dart looks roughly like this. The exact text varies between versions, so treat it as a reading aid and never edit it:
extension GetItInjectableX on GetIt {
GetIt init({
String? environment,
EnvironmentFilter? environmentFilter,
}) {
final gh = GetItHelper(this, environment, environmentFilter);
gh.lazySingleton<UserRepository>(() => ApiUserRepository());
gh.factory<ProfileViewModel>(
() => ProfileViewModel(gh<UserRepository>()),
);
return this;
}
}The generator read the ProfileViewModel constructor, saw it needs a UserRepository, and wrote the wiring. It also orders registrations so that dependencies come first.
Starting the app
Call the initializer once, before runApp:
import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'injection.dart';
void main() {
configureDependencies(Environment.prod);
runApp(const MyApp());
}This is still your composition root. The only change is that the list of registrations is generated rather than typed.
Third-party classes with modules
You cannot add @injectable to a class you do not own, such as http.Client or SharedPreferences. For those, write a module: an abstract class annotated with @module, whose members describe how to build each object.
import 'package:http/http.dart' as http;
import 'package:injectable/injectable.dart';
@module
abstract class NetworkModule {
@lazySingleton
http.Client get client => http.Client();
}A getter or method in a module becomes a registration. Any parameters of a module method are resolved from the container, so a module can also build objects that depend on other registered types.
Some objects need asynchronous setup. Annotate the member with @preResolve and return a Future. The generator then makes init return a Future<GetIt>, so you must await it in main:
@module
abstract class StorageModule {
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}@InjectableInit()
Future<void> configureDependencies(String environment) async =>
getIt.init(environment: environment);Make main async and await configureDependencies(...). If you forget the await, the app may start before the preferences are ready.
Environments for fakes
Environments let one codebase register different implementations in different builds. Mark each implementation with the environments where it applies:
@Injectable(as: UserRepository, env: [Environment.test])
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
@LazySingleton(as: UserRepository, env: [Environment.dev, Environment.prod])
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}When you call getIt.init(environment: Environment.test), only registrations with no environment, plus those that include test, are added. Registrations that list other environments are skipped.
You can use this in widget or integration tests. For plain unit tests, passing a fake through the constructor, as in the testing chapter, remains simpler and does not need the container at all.
If you reuse one getIt across several tests, call await getIt.reset() before each init. Otherwise get_it throws an error because the type is already registered.
Constructor parameters and named registrations
Some classes need a value that only the caller knows, such as a user ID. Mark that constructor parameter with @factoryParam. The class must be registered as a factory.
@injectable
class UserDetailViewModel extends ChangeNotifier {
UserDetailViewModel(this._repository, @factoryParam this.userId);
final UserRepository _repository;
final int userId;
}You then request it with getIt<UserDetailViewModel>(param1: 42). Parameters marked @factoryParam are not looked up in the container. The generator passes them through from param1 and param2. A class can use at most two.
When two implementations share a type, such as two String base URLs, use @Named('name') on both the registration and the constructor parameter.
Gotchas
- Generated code goes stale. If you change a constructor and do not rerun
build_runner, the old wiring stays in the config file. Runwatchwhile developing, and runbuildin CI. - Errors arrive at build time. If a required type has no registration, the generator reports a missing dependency while building. This is an improvement over hand-written
get_it, which fails when the code runs. - Duplicate registrations. Two classes registered as the same abstract type with overlapping environments cause an error or a silent override. Keep environments disjoint.
- Hidden global state.
injectabledoes not change the service locator trade-offs. Classes should still receive dependencies through their constructors and not callgetItinternally. - Generated files in version control. Teams differ on whether to commit
*.config.dart. Committing it makes fresh clones build faster. Ignoring it avoids merge conflicts. Pick one and apply it to the whole team.
When injectable is worth it
It pays off when you have dozens of registrations, several developers, or multiple environments. For a small app with five services, the hand-written setupLocator() is shorter and has no build step. Riverpod and Provider do not need it, because their providers are already declared in plain Dart.
Exercise
Your ProfileViewModel is annotated with @injectable and takes a UserRepository. Your ApiUserRepository is annotated with @lazySingleton (without as:). The build succeeds, but getIt<ProfileViewModel>() throws at runtime or the generator reports a missing dependency. Why, and how do you fix it?
Show answer
Without as: UserRepository, the generator registers the class under its own type, ApiUserRepository. Nothing is registered as UserRepository, so the view model's constructor parameter cannot be resolved. Change the annotation to @LazySingleton(as: UserRepository) and rerun dart run build_runner build --delete-conflicting-outputs.
Exercise
You want the same app to use ApiUserRepository in production and FakeUserRepository in widget tests, both resolved as UserRepository. What do you add to each class, and what do you pass to init?
Show answer
Give each class an environment list: @LazySingleton(as: UserRepository, env: [Environment.prod]) on the real class and @Injectable(as: UserRepository, env: [Environment.test]) on the fake. Call getIt.init(environment: Environment.test) in tests, after await getIt.reset(), and Environment.prod in main.