How to use Timer and periodic in Flutter

If you need to execute a piece of code after some time in Flutter you have to use Timer class. Timer class will allow specifying the time which you need to delay the execution and after that time period code will be executed inside the Timer.

    
    import 'dart:async';

    Timer(Duration(seconds:2),(){
          setState(() {
            greeting = "After Some time";
          });
        });
    

For the duration you can set any value based on your need. It accept seconds, minute, hours etc.

    
    Timer(Duration(minutes:2),(){
      setState(() {
        greeting = "After Some time";
      });
    });

    Timer(Duration(hours:1),(){
          setState(() {
            greeting = "After Some time";
          });
        });
    

Execute Periodically in Flutter

Timer will only execute a method single time. But if you need to execute method periodically in specific time period you can use periodic factory method in Timer class

    
   Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        greeting = "After Some time ${DateTime.now().second}";
      });
    });
    

This will set the value to the greeting variable in every 1 second.

How to stop/cancel period execution

you can use cancel method to stop the execution of timer by it self based on the condition.

    
  Timer.periodic(Duration(seconds: 1), (timer) {
      if(DateTime.now().second ==4){ //Stop if second equal to 4
        timer.cancel();
      }
      setState(() {
        greeting = "After Some time ${DateTime.now().second}";
      });
    });
    

if you need to stop the time from the outside of the method , you can keep the reference of the timer and call the cancel method from there.

    
    Timer _timer;
    
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
          setState(() {
            greeting = "After Some time ${DateTime.now().second}";
          });
        });
    
    FlatButton(
    	onPressed: (){
           _timer.cancel();
      }, child: Text("Stop")
    )
    
You Will Like Also