Flutter: How to stop timer after N seconds interval?

2.8k Views Asked by At

I am using below code to start the timer

Timer Snippet:

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


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

What I all want is to stop this timer after specific(N) timer interval.

3

There are 3 best solutions below

0
On BEST ANSWER

Since you want to cancel the Timer after a specific number of intervals and not after a specific time, perhaps this solution is more appropriate than the other answers?

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(); }
 );
0
On

Alternatively to Future.delayed(), you can also use

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

The Timer class exposes a couple extra methods like .cancel(), .tick, and isActive, so prefer it if you see yourself needing them down the road.

0
On

You can use a Future.delayed.

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