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?
CodePudding user response:
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