Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the timer in flutter?

Tags:

timer

flutter

I have created a timer in flutter and everything works fine. Now I can't figure out how to dismiss the timer after I started it.
The docs say that you can cancel it by calling void cancel() but I don't understand the implementation.

How am I supposed to call it?
And is it the right approach?

  static const timeout = const Duration(seconds: 5);
  static const ms = const Duration(milliseconds: 1);

  startTimeout([int milliseconds]) {
    var duration = milliseconds == null ? timeout : ms * milliseconds;
    return new Timer(duration, handleTimeout);
  }

  void handleTimeout() {  // callback function
    Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
        builder: (BuildContext context) => new ScorePage(quiz.score, quiz.length)),(Route route) => route == null);
    return;
  }
like image 321
jericho Avatar asked Jul 27 '18 13:07

jericho


People also ask

How do I stop my timer from fluttering?

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().

How do you use duration in flutter?

To create a new Duration object, use this class's single constructor giving the appropriate arguments: const fastestMarathon = Duration(hours: 2, minutes: 3, seconds: 2); The Duration represents a single number of microseconds, which is the sum of all the individual arguments to the constructor.


1 Answers

Just keep a reference to the time and cancel it when you don't need it anymore

var timer = startTimeout(100);
...
timer.cancel();
like image 200
Günter Zöchbauer Avatar answered Oct 03 '22 20:10

Günter Zöchbauer