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
CodePudding user response:
On the onInit()
function try to use this:
Replace the Timer t
-> timer
void onInit() {
super.onInit();
timer = Timer.periodic(const Duration(seconds: 5), (timer) {
print('timer is running');
});
}
}
CodePudding user response:
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();
}