当 GetxController 在 flutter 中被删除时,定时器永远不会被取消
假设我有两个屏幕(屏幕 A 和屏幕 B)。我使用以下方法从屏幕 A 导航到屏幕 B:
Get.toNamed('/screen_b');
屏幕 b 中有一个计时器,用于调用函数或打印语句。计时器代码位于 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');
}
}
我尝试使用 onDispose & 取消计时器GetxController 提供的 onClose 方法,但看起来计时器永远不会被取消。当我导航回屏幕 A 时,打印语句 **timer is running**
继续永远运行,并且该语句打印了 6/7 次。我做错了什么?当我从屏幕 B 返回到屏幕 A 时,Getx 打印以下语句
[GETX] CLOSE TO ROUTE /screen_b
[GETX] "Controller" onDelete() called
[GETX] "Controller" deleted from memory
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
onInit()
函数上尝试使用这个:替换
Timer t
->计时器
On the
onInit()
function try to use this:Replace the
Timer t
->timer
我确实遇到了与您上次相同的问题,当时您已经删除了控制器,但如果安装了计时器,时间仍然会像我一样滴答作响。
尝试将其放入 onClose 中
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.
try to put this in onClose