Sobes.tech
Junior — Middle

Can you explain the principle of dependency injection in Dart and how to use it?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in Dart is a way to pass necessary objects (dependencies) into classes or functions instead of creating them inside. This increases testability and flexibility of the code.

In Dart, DI can be implemented in various ways:

  • Constructor Injection — dependencies are passed through the class constructor.
  • Service Locator — a global object that provides dependencies on demand.
  • DI packages — for example, get_it for service locator or injectable for code generation.

Example of constructor injection:

class ApiService {
  void fetchData() {
    print('Fetching data');
  }
}

class Repository {
  final ApiService apiService;

  Repository(this.apiService);

  void load() {
    apiService.fetchData();
  }
}

void main() {
  final apiService = ApiService();
  final repository = Repository(apiService); // Dependency injection

  repository.load();
}

Here, Repository does not create ApiService itself but receives it from outside, which makes it easier to replace ApiService with a mock for tests or another implementation.

Can you explain the principle of dependency injection… - sobes.tech