如何在flutter中完成所有先前的异步功能?

时间:2019-11-18 12:08:16

标签: asynchronous flutter dart

我刚刚创建了将运行异步功能的按钮。该功能将等待4秒钟并打印。如果我多次单击按钮,它将打印所有点击。我想在单击按钮后,删除所有以前的异步功能并留下最后的点击。这是我的以下代码。

void asyncFunction(){
    Timer(Duration(seconds: 4),() async{
      print('something');
    });
  } 

那么如何在flutter中完成所有先前的异步功能?

2 个答案:

答案 0 :(得分:0)

声明一个计时器以稍后将其停止

Timer timer;

void asyncFunction() {
    timer = Timer(Duration(seconds: 1), () async {
      print('something');
    });

   onPressed: () {
  if(timer != null)
   timer.cancel();

   asyncFunction();
 }

答案 1 :(得分:0)

每次运行功能时,都需要取消以前的运行计时器。将计时器声明为状态,以作为当前异步执行的指针。

Timer _timer;

void asyncFunction() {
  _timer?.cancel();
  _timer = Timer(
    const Duration(seconds: 4),
    () => print('something'),
  );
}