-
Notifications
You must be signed in to change notification settings - Fork 3
Dependency Injection
Dustin Catap edited this page Jun 19, 2024
·
2 revisions
Since Flutter does not support reflection (dart:mirrors
), the project uses injectable
as our dependency injection and service locator.
get_it is used as the IoC container of the project.
injectable is used with get_it to generate code for your dependency registrations.
Registration is called before running the application, as show here in our main.dart
:
void main() {
...
ServiceLocator.registerDependencies();
...
}
The class MyServiceImpl
is annotated with @LazySingleton
, meaning this class will only be initialized (once and only when needed) when resolving MyService
.
import 'package:injectable/injectable.dart';
abstract class MyService{}
@LazySingleton(as: MyService)
class MyServiceImpl implements MyService {}
💡 TIP
- Use the snippet shortcut
dep
to create an abstract and concrete classes similar above.
Given that you registered AppLogger
:
import 'package:injectable/injectable.dart';
abstract class AppLogger{
void log(String message);
}
@LazySingleton(as: AppLogger)
class AppLoggerImpl implements AppLogger {
@override
void log(String message) => /* do logging */;
}
You can resolve a dependency using the ServiceLocator.instance
:
Future<void> main() async {
// register first
ServiceLocator.registerDependencies();
// resolve
final appLogger = ServiceLocator.instance<AppLogger>();
appLogger.log('Hello World');
}