Updated 27 April 2023
It is important to follow the best possible practices when building up a production-level application in order to make the application more powerful and stable; dependency injections are one of the techniques which can be used to achieve this. Simply put, dependency injection is a way to inject an instance of one class into another. It also offers shared instances which are highly helpful in state management by organizing the code at a higher level.
Check out more about our Flutter app development.
We can use dependency injection in a flutter with GetX.
Let’s continue the further process to start the implementation of dependency injection in a flutter.
1 2 |
dependencies: get: ^4.6.5 |
Step-1 To inject the object of the class use “Get.put”
When this method is used, the dependency will load immediately and can be used directly by implementing the code given below:
1 2 3 4 5 6 7 8 9 10 11 12 |
class FirstScreen extends StatelessWidget { // Controller dependency injected Controller controller = Get.put(Controller()); @override Widget build(BuildContext context) { // It can be used directly return Text(controller.name); } } |
we can also use the tag property to store multiple instances of the same class.
1 2 3 4 5 |
class ScreenOne extends StatelessWidget { Controller controllerOne = Get.put(Controller(), tag: 'tagOne'); Controller controllerTwo = Get.put(Controller(), tag: 'tagTwo'); } |
Step-2 To find the controller in our application lifecycle after injecting use “Get.find”
We can also use the Get.find
tag property in case of multiple shared instances which need to be updated individually. Use the code mentioned below to achieve this:
1 2 3 4 5 6 |
class ScreenTwo extends StatelessWidget { Controller controller = Get.find(); Controller controllerOne = Get.find(tag: 'tagOne'); Controller controllerTwo = Get.find(tag: 'tagTwo'); } |
The dependencies will be deleted if the route used Get.put
is removed from the navigation stack. Hence, we need to prevent this and keep the dependencies in the internal memory for the entire app session using permanent properties as shown below:
1 |
Get.put(Controller(), permanent: true); |
As a result of “permanent: true”, you will overcome the above route stack issue.
In this article, we have gone through the implementation of GetX dependency injection techniques. This technique offers an efficient and steady way of managing dependency injection. Hope this article has made the topic more comprehensive for you.
Thank you so much for reading! If you want to read more about the topic then click here.
Happy Coding!! 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.