Issue
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
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');
});
}
}
Answered By - Kei Credo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.