2

I initiate network request in GetXController, after network call back, I should judge this controller/this page is dealloc or not. 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:

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

So my question is how to write in GetX controller?

zhouxinle
  • 429
  • 5
  • 16
  • you could use reactive objects to deal with such situation ... and moreover you may override the dispose method and could call your_controller.dispose() to dispose the controller if not mounted. And one more tip is to cancel the network request while disposing your controller. – Ankit Kumar Maurya Mar 11 '22 at 04:08
  • you can use isClosed – Hooman Mar 11 '22 at 17:15

3 Answers3

3

There is a property called isClosed in GetxController so you can use it instead of mounted

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

mounted can only be called inside Stateful widgets, so you can't use it inside a 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();
}
djalmafreestyler
  • 1,703
  • 5
  • 21
  • 42
0

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.

On the other hand, you can check on mounted before calling the method, like this:

   // ....
   onPressed: () {
      if (mounted) {
        controller.sendRequest();
      }
    },
    // ....
Gwhyyy
  • 7,554
  • 3
  • 8
  • 35