Junior — Middle
Explain the concept of dependency injection and its role in software development.
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern in which objects receive their dependencies from outside rather than creating them themselves. This promotes loose coupling of components and simplifies testing.
In the context of Flutter, DI helps manage state and services, making it easier to replace implementations and reuse code.
Example: instead of creating an instance of a service inside a widget, the service is passed through the constructor or via a provider (for example, using the provider package or get_it).
class ApiService {
void fetchData() {
// ...
}
}
class MyWidget extends StatelessWidget {
final ApiService apiService;
MyWidget({required this.apiService});
@override
Widget build(BuildContext context) {
apiService.fetchData();
return Container();
}
}
// At the point of widget creation
final apiService = ApiService();
MyWidget(apiService: apiService);
Thus, DI increases modularity, facilitates component replacement, and simplifies testing.