The Get.create Method
Learn to use Get.create to serve a specific use case.
We'll cover the following...
Background
Traditionally, dependency injection is used to share the same class instance across multiple widgets. However, in some cases, we may wish to create new instances to maintain separate states of the same class. This is when Get.create comes into the picture. When we initialize a dependency using Get.create, a new instance of the dependency is created every time Get.find is called.
This feature becomes instrumental when we have a page with multiple widgets that use the same controller but do not share the same state of the controller. For example, a shopping cart page:
In this case, all the widgets are using the same controller. However, each widget is connected to a unique instance which allows it to maintain its state independently.
Implementation of shopping cart
Let’s see how we can utilize Get.create to implement a functional shopping cart:
Create a controller class named
ShoppingController. Inside, add two variables to keep track of the quantity of a single product and the total count of all products.
class ShoppingController extends GetxController {RxInt quantity = 0.obs;RxInt total = 0.obs;}
We create a bindings class called
ShoppingBindingand inject dependencies using two methods—Get.createandGet.put...