Gwhyyy
Gwhyyy

Reputation: 9196

what is Get.create() in the Getx package and what it does

reading the Getx package documentation, I faced this method:

  Get.create<ShoppingController>(() => ShoppingController()); 

and it says:

Get.create(()=>Controller()) will generate a new Controller each time you call Get.find(),

but, I don't seem to understand what this means and how it differs from the Get.put() and Get.lazyPut().

Upvotes: 2

Views: 1620

Answers (2)

Faheem Ahmad
Faheem Ahmad

Reputation: 173

it is now Get.spawn in the latest version of GetX packaged version 5.0.

Make sure to update the package first then use this.

This will give no errors.

Upvotes: 0

Gwhyyy
Gwhyyy

Reputation: 9196

I found the answer for that question.

The big difference between

Get.create<ShoppingController>(() => ShoppingController()); 

And :

Get.put(ShoppingController());

Both of them are used in injecting dependencies in the a Flutter app, But Get.put<T>(T()) injects it just one time and whenever we call Get.find<T>() it looks up for that exact dependency and return it, so we can rememeber this:

Get.put<T>(()) inject a dependency and whatever time we call Get.find<T>() across the entire app, the same T is returned.

In the other side, Get.create<V>(() => V) also inject a dependency in a Flutter app, But every time we call Get.find<V>(), it doesn't return the same V, it creates a new instance of V, then return it, so we can rememeber this:

Get.create<V>(() => V) don't return the same instance, it creates a new one every time Get.find<V>() is called.

Get.put(T()) :

class ControllerOne extends GetxController {
int number = 10;
increment() {
 number += 10;
 }
}


final controllerOne =  Get.put<ControllerOne>(ControllerOne());

final controllerOneFinder = Get.find<controllerOne>();

controllerOneFinder.increment();

final controllerOneSecondFinder = Get.find<controllerOne>();

print(controllerOneFinder.number); // 20

print(controllerOneSecondFinder.number); // 20

it stay the same.

Get.create(() =>T) :

class ControllerTwo extends GetxController {
int secondNumber = 10;
increment() {
 secondNumber += 10;
 }
}


final controllerTwo =  Get.create<ControllerTwo>(() => (ControllerTwo());

final controllerTwoFinder = Get.find<ControllerTwo>();

controllerTwoFinder.increment();

final controllerTwoSecondFinder = Get.find<ControllerTwo>();


print(controllerTwoFinder.number); // 20

print(controllerTwoSecondFinder.number); // 10

Each one is different than the other. (controllerTwoSecondFinder == controllerTwoFinder) is false.

Upvotes: 5

Related Questions