简体   繁体   English

Flutter - 如何使用安装在 GetX 中

[英]Flutter - How to use mounted in GetX

I initiate.network request in GetXController, after.network call back, I should judge this controller/this page is dealloc or not.我在GetXController发起.network请求,.network回调后,判断这个controller/这个page是否dealloc。 If this page is not dealloced, update Page.如果未释放此页面,请更新页面。 If this page is dealloced, I do noting.如果这个页面被释放,我不会注意到。 As I know, I can write below codes in flutter origin:据我所知,我可以在 flutter 来源中编写以下代码:

if (mounted) {
   // update page
   setState({
   });
}

So my question is how to write in GetX controller?所以我的问题是GetX controller怎么写?

There is a property called isClosed in GetxController so you can use it instead of mounted GetxController中有一个名为isClosed的属性,因此您可以使用它而不是mounted

class MyController extends GetxController{
...
  fun() {
    // some code
    if(this.isClosed) return;
    // code that you want not execute it
  }
...
}

mounted can only be called inside Stateful widgets, so you can't use it inside a Controller. mounted 只能在 Stateful widgets 内部调用,所以你不能在 Controller 内部使用它。

If you are using named routes I think you can get the current name of the page and do something.如果您使用的是命名路由,我认为您可以获得页面的当前名称并做一些事情。

if(Get.routing.current == "/home"){
   doSomething();
}

the mounted bool is specific only for the StateFulWidget , I could think of passing it as a Stream<bool> to the controller, then use it, But , this is not the ideal solution and it can be very problematic. mounted bool 仅适用于StateFulWidget ,我可以考虑将其作为Stream<bool>传递给 controller,然后使用它,但是,这不是理想的解决方案,而且可能会出现很多问题。

On the other hand, you can check on mounted before calling the method, like this:另一方面,您可以在调用方法之前检查mounted ,如下所示:

   // ....
   onPressed: () {
      if (mounted) {
        controller.sendRequest();
      }
    },
    // ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM