[英]Periodic timer disposal not working in Flutter
I have a periodic timer of 5 seconds, where I am calling a function.我有一个 5 秒的周期性计时器,我在其中调用 function。
timer3 = Timer.periodic(
Duration(seconds: 5),
(Timer t) => function());
The function is as below; function如下;
Future<dynamic> function() async {
var url = "https://rtdjiigwvh.execute-api.us-east-2.amazonaws.com/v1/preview_checkout";
Map data = {};
String body = json.encode(data);
var res = await http
.post(url, headers: {"Content-Type": "application/json"}, body: body)
.then((value) {
location = json.decode(value.body)["Location"].toString();
print(location);
if(location == 'ENTRY')
setState(() {
entry = true;
});
else if(location == 'EXIT')
setState(() {
exit = true;
@override
void dispose() {
timer3?.cancel();
super.dispose();
}
});
if(exit == true)
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
NextScreen()));
});
}
Here when the boolean variable exit
is true, I want the screen to redirect to the next screen, and also want to stop the polling which I am doing using the timer.在这里,当 boolean 变量
exit
为真时,我希望屏幕重定向到下一个屏幕,并且还想停止使用计时器进行的轮询。 Therefore I have used the dispose
function for the timer to stop, but the problem is it won't stop right there and keeps on polling and refreshing the NextScreen continuously for every 5 seconds.因此,我使用
dispose
function 来停止计时器,但问题是它不会停在那里,而是每 5 秒不断轮询和刷新 NextScreen。 Kindly help me resolve this issue.请帮我解决这个问题。 Thanks in advance!
提前致谢!
Dispose method should be defined outside of function
method. Dispose 方法应在
function
方法之外定义。 Move:移动:
@override
void dispose() {
timer3?.cancel();
super.dispose();
}
outside and it will be automatically called when the statefulwidget gets disposed.在外面,当 statefulwidget 被处理时,它将被自动调用。
You can use您可以使用
Future.delayed(Duration(seconds : 5)).then((){
function();
});
instead of timer而不是计时器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.