0

I have a timer setup like this. I want the Timer to be reset and reinitialized with the new timevalue as and when changingTimeValue changes. What are the ways in which I can do this ?

snakeUpdateTimer = Timer.periodic( changingTimeValue , (timer){
      snakeBloc.add(SnakeMoveEvent()) ;
    });
0

2 Answers 2

2
Timer snakeUpdateTimer;

...

set changingTimeValue(Duration duration) {
    snakeUpdateTimer?.cancel();
    snakeUpdateTimer = Timer(
      duration,
      () => snakeBloc.add(SnakeMoveEvent()),
    );
  }

...

RaisedButton(
  child: Text("Click to reset Timer"),
  onPressed: (){
    changingTimeValue= Duration(seconds: 3);
  },
)

When you assign Duration to changingTimeValue, it will cancel the old timer and creates new one.

If you also want to periodically reset the timer after timeout, then use

set changingTimeValue(Duration duration) {
  snakeUpdateTimer?.cancel();
  snakeUpdateTimer = Timer.periodic(
    duration,
    (timer) => snakeBloc.add(SnakeMoveEvent()), 
    //timer contains number of cycles finished(timer.tick)
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

Timer.periodic constructor or Timer constructor. Timer.periodic is initialized once with the duration and it invokes the callback on the intervals that is provided as duration. Whereas Timer constructor creates a timer that ticks only once. Based on your requirement you can used any of these.

Following is the code that allows you to change the time of the timer:

Timer _timer; // global variable.

void updateTimerDuration(Duration changingTimeValue) {
  if (_timer != null && _timer.isActive) _timer.cancel();

  // if you want timer to tick only once.
  _timer = Timer(changingTimeValue, () {
    snakeBloc.add(SnakeMoveEvent());
  });

  // if you want timer to tick at fixed duration.
  _timer = Timer.periodic(changingTimeValue, (timer) {
    snakeBloc.add(SnakeMoveEvent());
  });
}

I hope it helps, in case of any doubts please comment.

2 Comments

Please show me the code as to how to implement the time change handling.
I have updated my answer, hope it helps you. In case of doubt please let me know. And if it works for you then please accept and up-vote this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.