Junior — Middle
Can you explain the concept of service locator and its main functions?
sobes.tech AI
Answer from AI
Service locator is a design pattern used for managing dependencies in an application. Its main function is to centrally store and provide service objects (such as classes for network operations, database, logging, etc.) upon request.
In Flutter, the service locator is often used to simplify access to services without the need to pass them through constructors or widget contexts.
Examples of core functions of a service locator:
- Registering services (singleton or factories)
- Retrieving registered services by type
Example using the get_it package:
import 'package:get_it/get_it.dart';
final getIt = GetIt.instance;
void setup() {
getIt.registerSingleton<ApiService>(ApiService());
}
class ApiService {
void fetchData() {
print('Fetching data...');
}
}
void main() {
setup();
var api = getIt<ApiService>();
api.fetchData();
}
Thus, the service locator simplifies dependency management and enhances code modularity.