get.put 和 get.lazyput 之间的区别

sai*_*man 11 dart flutter flutter-getx

我对 的依赖注入很陌生,所以有人可以向我解释和Getx的好处并告诉我它们有什么区别吗?Get.put()Get.lazyPut()

Tua*_*uan 25

简短回答

  • Get.put()立即投入
  • Get.lazyPut()当你需要的时候会放


Ivo*_*ers 11

据我了解,put已经将类的实例直接放入内存中,而lazyPut只是将其构建器放入其中。

一个好处lazyPut是它可以节省内存,直到您实际find使用为止。您还可以在构建器中为其添加更复杂的代码。另一个好处lazyPut是你还可以fenix: true对它说,这意味着它可以被重建,以防它之前被丢弃。

我认为使用的唯一好处put是它find应该比调用时稍微快一些,因为它不需要先调用构建器来获取实例。不知道还有没有其他好处。


Gwh*_*yyy 6

获取.put() :

将注入依赖项并在注入时立即开始执行,我的意思是,它的生命周期方法将在您onInit()onReady()这样注入时执行:

class ControllerOne extends GetxController {
  int a = 1;
  @override
  void onInit() {
    print('ControllerOne onInit');
    super.onInit();
  }

  @override
  void onReady() {
    print('ControllerOne onReady');
    super.onReady();
  }
}


final controller = Get.put(ControllerOne()); // will inject that dependecy, and immediately will call onInit() method  then onReady() method
Run Code Online (Sandbox Code Playgroud)

调试日志:

 ControllerOne onInit
 ControllerOne onReady
Run Code Online (Sandbox Code Playgroud)

Get.lazyPut() :

还将注入一个依赖项,但它不会开始执行生命周期方法onInit()onReady()直到您真正使用该控制器:

 class ControllerTwo extends GetxController {
  int b = 2;
  @override
  void onInit() {
    print('ControllerTwo onInit');
    super.onInit();
  }

  @override
  void onReady() {
    print('ControllerTwo onReady');
    super.onReady();
  }
}

final controller = Get.lazyPut(() => ControllerTwo()); // will inject that dependecy, and wait until it's used then it will call onInit() method, then onReady() method
Run Code Online (Sandbox Code Playgroud)

调试日志:

 /* nothing will be printed right now */
Run Code Online (Sandbox Code Playgroud)

但如果我们确实使用控制器,举个例子:

controller.b = 10;
Run Code Online (Sandbox Code Playgroud)

然后控制器将开始运行:

调试日志:

 ControllerTwo onInit
 ControllerTwo onReady
Run Code Online (Sandbox Code Playgroud)

希望这能澄清这一点!