Sub topic 13
Generating Registrations with `injectable`
This chapter assumes you know Dart classes, abstract classes, implements, Flutter widgets, BuildContext, Future, and basic ChangeNotifier state management. It also assumes you have seen get_it registration and lookup.
Manually registering every dependency works well in a small app:
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);As an app grows, this setup can become long and easy to forget. injectable is a code-generation package that creates these registrations from annotations in your Dart code. You describe the classes and their lifetimes. A generated file contains the get_it registration code.
Add `injectable` to the project
Add the runtime packages and development tools to pubspec.yaml:
dependencies:
get_it: ^8.0.0
injectable: ^2.5.0
dev_dependencies:
build_runner: ^2.4.0
injectable_generator: ^2.6.0Run:
flutter pub getbuild_runner runs generators. injectable_generator reads your annotations and writes registration code.
Annotate dependencies
Create an initialization file and mark it with @InjectableInit:
// service_locator.dart
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
final getIt = GetIt.instance;
@InjectableInit()
void configureDependencies() => getIt.init();Now annotate classes that should be registered:
// dependencies.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 {
return 'User $id';
}
}
@injectable
class ProfileViewModel {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
}
}@LazySingleton(as: UserRepository) tells injectable to register one lazily created ApiUserRepository under the UserRepository abstraction. @injectable registers ProfileViewModel as a factory by default. Its constructor parameter tells the generator which dependency to resolve.
Run the generator:
dart run build_runner buildThis creates a generated file, commonly named service_locator.config.dart. The generated file contains code similar to:
// service_locator.config.dart
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'dependencies.dart';
extension GetItInjectableX on GetIt {
Future<GetIt> init() async {
registerLazySingleton<UserRepository>(() => ApiUserRepository());
registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
return this;
}
}The generated file is implementation detail. Do not edit it by hand. Regenerate it after changing annotations or constructors.
Initialize the generated registrations
Import the generated extension from the initialization file. The generator normally adds this import for you:
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'service_locator.config.dart';
final getIt = GetIt.instance;
@InjectableInit()
Future<void> configureDependencies() => getIt.init();Initialize before building the application:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureDependencies();
runApp(const MyApp());
}await matters when generated registrations include asynchronous setup, such as opening a database or loading configuration. Code that calls getIt<ProfileViewModel>() must run after initialization.
Lifetimes and environments
Use the annotation that matches the object’s lifetime:
| Annotation | Typical behavior | Example |
|---|---|---|
| `@injectable` | New instance for each lookup | View model |
| `@singleton` | Created immediately and reused | In-memory cache |
| `@lazySingleton` | Created on first lookup and reused | API client |
You can also register different implementations for environments such as testing and production. This keeps environment-specific wiring out of application code, but it requires careful generator configuration and clear names.
Common errors
- Forgetting
build_runner, so the generated file does not exist. - Changing a constructor without regenerating registrations.
- Calling
getItbeforeconfigureDependencies. - Registering two implementations for the same abstraction without a named registration.
- Giving a short-lived object a reference to a resource that should be disposed earlier.
injectable reduces repetitive registration code, but it adds generated files, annotations, and build steps. It fits projects that already use get_it and have enough dependencies for manual wiring to become difficult to maintain.
Exercise
What command should you run after adding @LazySingleton(as: UserRepository) to a repository class?
Show answer
Run dart run build_runner build, then initialize the generated registrations before resolving the repository.