Component - Dependency injection (GetIt)
This Flutter component shows how to use GetIt for dependency injection. It helps to manage and access shared objects like services easily across the app without passing them manually.
This Flutter component shows how to use GetIt for dependency injection. It helps to manage and access shared objects like services easily across the app without passing them manually.
Scaffold
├── AppBar
└── Center
└── Column
├── Text
└── ElevatedButtonGetIt in a Flutter app?MyService(). GetIt.instance.registerSingleton(() => MyService()); wrongly passes a function. GetIt.instance.registerFactory(() => MyService()); registers a factory, not a singleton. GetIt.instance.registerLazySingleton(MyService()); passes an instance to lazy singleton incorrectly.final getIt = GetIt.instance;
class Counter {
int value = 0;
void increment() => value++;
}
void main() {
getIt.registerSingleton(Counter());
final counter1 = getIt<Counter>();
final counter2 = getIt<Counter>();
counter1.increment();
print(counter2.value);
}Counter as a singleton means counter1 and counter2 point to the same instance.counter1.increment() increases value from 0 to 1. Since counter2 is the same instance, counter2.value is 1.final getIt = GetIt.instance;
void setup() {
getIt.registerFactory<MyService>(MyService());
}registerFactory method expects a function that returns a new instance each time, not an instance itself.MyService() directly is an instance, not a function. The correct usage is registerFactory(() => MyService()).registerFactory registers a function that returns a new instance on each call, matching the requirement.registerFactory(() => Service()), passing a function that creates a new instance.Pass the test and this pattern moves unknown