Flutter:如何在 N 秒间隔后停止计时器?

Flutter: How to stop timer after N seconds interval?

我正在使用下面的代码启动计时器

计时器片段:

 _increamentCounter() {
    Timer.periodic(Duration(seconds: 2), (timer) {
       setState(() {
         _counter++;
       });
    });
  }


 RaisedButton raisedButton =
        new RaisedButton(child: new Text("Button"), onPressed: () {
            _increamentCounter();
        });

我想要的是在特定的 (N) 个计时器间隔后停止此计时器。

您可以使用 Future.delayed.

Future.delayed(const Duration(seconds: n), () => _increamentCounter());

除了Future.delayed(),您还可以使用

Timer(const Duration(seconds: n), () => _increamentCounter());

Timer class 公开了一些额外的方法,例如 .cancel().tickisActive,所以如果您发现自己需要它们,请选择它在路上。

由于您想在特定的 间隔 之后而不是在特定的 时间 之后取消 Timer,也许这个解决方案比其他答案更合适?

Timer _incrementCounterTimer;


_incrementCounter() {
    _incrementCounterTimer = Timer.periodic(Duration(seconds: 2), (timer) {     
        counter++; 

        if( counter == 5 ) // <-- Change this to your preferred value of N
            _incrementCounterTimer.cancel();

        setState(() {});
    });
}


 RaisedButton raisedButton = new RaisedButton(
    child: new Text("Button"), 
    onPressed: () { _incrementCounter(); }
 );