'Timer is never cancelled when GetxController is deleted in flutter

Let's say I have two screens (Screen A & Screen B). I navigate from Screen A to B using the following method:

Get.toNamed('/screen_b');

I have a timer in screen b that calls a function or prints a statement. The timer code is inside GetxController.

class Controller extends GetxController{

 
  Timer? timer;

@override
  void onInit() {
    super.onInit();
      timer = Timer.periodic(const Duration(seconds: 5), (Timer t) {
        print('timer is running');
        //DO SOMETHING
      });

    }

  }

@override
  void dispose() {
    print('I am disposed');
    timer!.cancel();
    super.dispose();

  }

  @override
  void onClose() {
    timer!.cancel();
    super.onClose();
    print('I am closed');


  }

}

I've tried to cancel timer using onDispose & onClose methods provided by GetxController but it looks like timer is never cancelled. When I navigate back to Screen A, the print statement **timer is running** keeps on running forever and the statement is printed 6/7 times. What did I do wrong? When I go back from Screen B to Screen A, Getx prints the following statement

[GETX] CLOSE TO ROUTE /screen_b
[GETX] "Controller" onDelete() called
[GETX] "Controller" deleted from memory


Solution 1:[1]

I do have same problem as you last time when you already deleted the controller but the time still run ticking as i did is if the timer is mounted.

ifTimerMounted(){
 final itimer = timer == null ? false : timer!.isActive;
 if(itimer){
   timer!.cancel();
 }else{
  // Or Do Nothing Leave it Blank
  log('Timer Stop Running')
  }
}

try to put this in onClose

@override
  void onClose() {
    super.onClose();
   ifTimerMounted();  
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arbiter Chil