Dependency injection without passing objects in functions in Flutter using GetX?

Issue

Dependency injection is all about passing objects to a class through either a constructor or a setter function.

So, if we use GetX then for dependency injection, the way would be to use Get.put().

But we aren’t passing the object through any function to the following class so how can this be classified as "dependency injection"?

class HomePage extends StatelessWidget {        
  Controller controller = Get.put(Controller());    
}

Now, if we have to pass another controller to this class from another class (using GetX), how do we do it?

https://medium.com/flutter-community/the-flutter-getx-ecosystem-dependency-injection-8e763d0ec6b9#:~:text=Dependency%20Injection%20is%20the%20technique,code%20at%20a%20greater%20level.

Solution

The idea of dependency injection is that once a controller has been initialized in any widget, Later widgets if need the controller they can simply get and not put every time.

Controller1 objectName=Get.find();

To try this, create a widget on page 1 and initialize the controller (PUT), create a button and send to page 2 and try to get the controller there. You will notice, that the controller is available instead of using put in all subsequent pages.

For using multiple controllers:

Controller1 controller1 = Get.put(Controller1());  
Controller2 controller2 = Get.put(Controller2());   

Note GetX knows the controller because on your controller class you write:

class Controller1 extends GetxController

Answered By – Godwin

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *