Sub topic 1
Dependency Injection in Flutter Apps: What Dependency Injection Solves
Prerequisites
This chapter assumes you know Dart classes, abstract classes, and the implements keyword. You should also understand Futures and async/await, and have a Flutter project to run the examples in.
What dependency injection solves
A dependency is any object that another class needs to do its job. A view model that loads a user profile depends on whatever fetches user data. If the view model creates that object itself, the two are tightly coupled. Changing the data source then means editing the view model, and testing the view model means reaching the real network.
Dependency injection (DI) is the practice of handing a class its dependencies from outside instead of letting it create them. The class declares what it needs, and something else supplies it.
Passing dependencies through constructors
The simplest form of DI is constructor injection. The class accepts its dependency as a constructor parameter and stores it.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}
class ProfileViewModel {
ProfileViewModel(this._repository);
final UserRepository _repository;
Future<String> load(int id) => _repository.fetchName(id);
}
void main() async {
final viewModel = ProfileViewModel(ApiUserRepository());
print(await viewModel.load(1)); // User 1
}The view model no longer decides which repository it uses. The caller does.
Depending on abstractions, not implementations
The constructor parameter has the type UserRepository, an abstract class, not ApiUserRepository. The view model therefore depends only on the contract. Any class that implements UserRepository can be passed in, including a fake used in tests.
A hard-coded dependency looks like this:
class ProfileViewModel {
final _repository = ApiUserRepository(); // Hard to change or test
}Wiring everything in one place
Something must still create the real objects. The composition root is the single place in the app where concrete classes are created and connected. Usually this is main(). Keeping this wiring in one file means the rest of the code never needs to know which implementation runs in production.
Exercise
In the example, why does ProfileViewModel take UserRepository in its constructor instead of ApiUserRepository?
Show answer
Declaring the abstract type lets any implementation be passed in, such as a fake for tests, without changing the view model.