Dependency Injection
GetIt and injectable for managing dependencies
Dependency injection decouples your code by providing dependencies from outside. GetIt is a popular service locator for Flutter.
Widgets that create their own dependencies are hard to test and tightly coupled. DI inverts the control.
// Tightly coupled (bad)
class UserPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Creates its own dependency
final repo = ApiUserRepository();
// Can't swap for testing
}
}
// Dependency injected (good)
class UserPage extends StatelessWidget {
final UserRepository repo;
UserPage({required this.repo});
// Can be API, fake, or mock
}Service Container
ApiClientSingleton
AuthServiceLazy
depends on: ApiClient
UserRepoFactory
depends on: ApiClient
PostRepoFactory
depends on: ApiClient
UserBlocFactory
depends on: UserRepo