Getx包中的Get.create()是什么,它做什么



阅读Getx包文档,我遇到了这个方法:

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

上面写着:

Get.create(()=>Controller())将在每次调用Get.find()时生成一个新的Controller,

但是,我似乎不明白这是什么意思,以及它与Get.put()Get.lazyPut()有何不同。

我找到了那个问题的答案。

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

:

Get.put(ShoppingController());

它们都用于在Flutter应用程序中注入依赖项,但是Get.put<T>(T())只注入一次,每当我们调用Get.find<T>()时,它都会查找确切的依赖项并返回它,因此我们可以记住这一点:

Get.put<T>(())注入一个依赖项,无论何时在整个应用程序中调用Get.find<T>(),都会返回相同的T

另一方面,Get.create<V>(() => V)也在Flutter应用程序中注入了一个依赖项,但是每次我们调用Get.find<V>(),它不会返回相同的V,它创建一个新的V实例,然后返回它,所以我们可以记住这个:

Get.create<V>(() => V)不会返回相同的实例,每次调用Get.find<V>()都会创建一个新的实例。

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

它保持不变。

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

每一个都是不同的。(controllerTwoSecondFinder == controllerTwoFinder) isfalse.

最新更新