flutter取消Future.delayed操作

在flutter中经常会用到延时任务,可能会用到Future.delayed,比如

await Future.delayed(Duration(seconds: myDuration)).then((_){

  checkAnswer("");
  jumpToNextQuestion();

});

然而有时候在这个任务未执行前 我们就关掉了页面,这时候就会报错。

怎么办?

答案是用timer代替。

  Timer t = Timer(Duration(seconds: myDuration), () {
    checkAnswer('');
    jumpToNextQuestion();
  });
  // and later, before the timer goes off...
  t.cancel();

 

你可能感兴趣的:(flutter)