【问题标题】:How to finish all previous async functions in flutter?如何在颤振中完成所有以前的异步功能?
【发布时间】:2019-11-18 12:08:16
【问题描述】:

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

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

那么如何在flutter中完成之前所有的异步函数呢?

【问题讨论】:

标签: asynchronous flutter dart


【解决方案1】:

每次运行函数时都需要取消之前的运行计时器。在你的状态中声明一个计时器作为当前异步执行的指针。

Timer _timer;

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

【讨论】:

    【解决方案2】:

    声明一个 Timer 稍后停止它

    Timer timer;
    
    void asyncFunction() {
        timer = Timer(Duration(seconds: 1), () async {
          print('something');
        });
    
       onPressed: () {
      if(timer != null)
       timer.cancel();
    
       asyncFunction();
     }
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2021-08-13
      • 2017-04-01
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多