Search code examples
flutterdartflutter-timer

Flutter: How to stop timer after N seconds interval?


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.


Solution

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