【问题标题】:Timer not cancelling flutter定时器不取消颤振
【发布时间】:2021-02-09 07:08:25
【问题描述】:

我需要一个计时器实例来在我的应用程序上运行,以便我可以在需要时取消并重新初始化它。但是,调用.cancel() 操作后,计时器不会取消。它只有在我从默认构造函数中调用它时才有效,但我想要一个可以随时取消的全局计时器;

Timer timer;

  timer = Timer.periodic(Duration(seconds: 10), (Timer t) async {
         //cancelling timer only works here e.g (t.cancel)
  print("loop operation");
        });

timer.cancel(); // calling this method outside the constructor don't work.

【问题讨论】:

  • 到目前为止,当人们声称 Timer 取消无效时,我看到的最常见错误是他们不小心创建了多个 Timer 对象并破坏了先前的引用。请发布一个可重现的示例并验证您没有泄漏Timers。
  • @jamesdlin 那是我的情况兄弟。现在修好了。谢谢

标签: flutter dart


【解决方案1】:

我遇到了类似的问题。这发生在我创建回调函数async之后。

我认为解决方案会因问题而异,具体取决于您的回调为什么是async

这不是一个解决方案,而是一个让您更接近解决方案的提示。

【讨论】:

    【解决方案2】:
    Timer timer;
    
    Timer.periodic(Duration(seconds: 10), (Timer t) async {
                timer = t;
                print("loop operation");
            });
    
    
    //inside a button callback
    timer??.cancel(); // perform null check as well before cancelling.
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2019-07-22
      • 2021-02-11
      • 2019-01-28
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多