3

I want to use GetX in my flutter project for state management. I don't know how I can achieve dependency injection with GetX though. Is it ok to use Get_it along with GetX in the same project? I feel like doing so makes the code cluttered. Or should I create a binding class with GetX and use it as initialBinding to achieve dependency injection?

I want to be able to inject dependencies into non-view classes. What is the best practice for this?

Using GetX + Get_it or is it possible with GetX alone?

Thanks

Shaw
  • 61
  • 1
  • 3

2 Answers2

7

It is possible to just use GetX and still be able to access dependencies form outside the widget tree.

///Inject
Get.put(CartService());
///Retrieve
CartService cartService = Get.find();

GetX has a built in service locator just as Get_it works. Although they don't share the same features the one you are looking for GetX does the trick.

You could use both, but if GetX already has this functionality built in and it works correctly I don't see why you would need to access get _it.(Maybe to use injectable?)

croxx5f
  • 5,163
  • 2
  • 15
  • 36
  • 2
    Thanks a lot. I just couldn't find any information on how to manage all the project's dependencies in one centralized location using GetX as it is done with Get_it package. So I think I should just create a separate class for dependencies and write all DI code in there. – Shaw Aug 30 '21 at 12:58
  • thanks. exactly I need to use injectable to inject different implementation of some services depending test or dev environment. I dont think I could achieve it with getX? – rsobies May 17 '22 at 08:55
  • No @rsobies, the code-gen and environment based dependencies are just AFAIK in the injectable package (which uses get_it under the hood). Either one you choose, injectable or getx, be consistent in your code and stick to one solution. – croxx5f May 17 '22 at 16:37
3

Dependency injection is so easy with Getx You can put all your dependencies (like database service and api service ...) in one class that extends from "Bindings"

class AppBinding extends Bindings {
  @override
  void dependencies() {
    Get.put(APIManager());
    Get.put(CacheManager());
    Get.put(GlobalRepository();
......
  }
}

and sets object from it in GetMaterialApp with initialBinding property

Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: AppBinding(), // <--- here
      ......
      home: SplashScreenView(),
    );
}