📅  最后修改于: 2023-12-03 15:15:15.396000             🧑  作者: Mango
GetIt is a simple, yet powerful service locator for Dart and Flutter projects. It allows you to register and retrieve objects throughout your application, eliminating the need for cumbersome dependencies and providing a cleaner, more efficient programming experience.
To use GetIt in your Flutter or Dart projects, simply add it as a dependency in your pubspec.yaml
file:
dependencies:
get_it: ^5.0.6
Then register your objects in the main()
function or any other location that makes sense:
import 'package:get_it/get_it.dart';
void main() {
GetIt.instance.registerSingleton<MyService>(MyService());
}
And retrieve your objects easily throughout your application:
final myService = GetIt.instance.get<MyService>();
GetIt supports both singleton and factory registrations. Singleton objects are created once and re-used throughout the lifetime of the application, while factory objects are created each time they are requested.
To register a singleton object, simply call registerSingleton()
and pass in the object you want to register:
GetIt.instance.registerSingleton<MyService>(MyService());
To register a factory object, call registerFactory()
and pass in a function that returns the object you want to register:
GetIt.instance.registerFactory<MyService>(() => MyService());
To retrieve an object that has been registered as a singleton, call get()
:
final myService = GetIt.instance.get<MyService>();
To retrieve an object that has been registered as a factory, call call()
:
final myService = GetIt.instance.call<MyService>();
By default, GetIt initializes objects as soon as they are registered. To improve performance, you can use lazy initialization to delay object initialization until the first time it's retrieved.
To use lazy initialization, simply pass true
as the second argument when registering your object:
GetIt.instance.registerSingleton<MyService>(MyService(), signalsReady: true);
Then use the isReady
property to determine if the object has been initialized:
if (GetIt.instance.isReady<MyService>()) {
final myService = GetIt.instance.get<MyService>();
}
GetIt supports strongly-typed generics to ensure type safety throughout your application. When registering an object, specify the type using generics:
GetIt.instance.registerSingleton<MyService>(MyService());
Then when retrieving the object, specify the same type:
final myService = GetIt.instance.get<MyService>();
GetIt automatically disposes of objects when they are no longer needed. For singleton objects, this occurs when the application is terminated. For factory objects, this occurs when the object is no longer being used.
GetIt is a powerful service locator for Dart and Flutter projects, simplifying the process of registering and retrieving objects throughout your application. By eliminating dependencies and improving performance with lazy initialization, GetIt provides a cleaner, more efficient programming experience.