Home > Back-end >  Multiple timers starting at once (Flutter)
Multiple timers starting at once (Flutter)

Time:10-02

So I have created a timer that I can start and stop with a button. Mostly works fine, however if I spam the button to start and stop it really fast, it seems to start multiple timers at once and as a result, the function gets fired a lot faster than one second. Is there anyway that I can keep it at one timer at a time or some sort of way to cancel all the timers at once (I am very new to flutter and timers).

to start the timer:

void startTimer() {
    Timer.periodic(Duration(seconds: seconds), (t) {
      setState(() {
        timer = t;
        randomNote = Random().nextInt(6);
        randomType = Random().nextInt(6);
      });
    });
  }

to stop the timer:

timer?.cancel();

I have tried adding an if statement to check if a timer is active so the code looks like this:

 void startTimer() {
    if (timer?.isActive != true) {
      Timer.periodic(Duration(seconds: seconds), (t) {
        setState(() {
          timer = t;
          randomNote = Random().nextInt(6);
          randomType = Random().nextInt(6);
        })
      });
    }
  }

But nothing changes.

CodePudding user response:

You can check if any timer is currently working or not. If there is some timer going on, just don't let the function to be triggered. To check if timer is working, you can look over here

CodePudding user response:

Well since you say if (timer?.isActive != true) isn't working, an alternative to that is this,

bool isTimerOn = false;
...
void startTimer() {
  if(!isTimerOn){ 
    isTimerOn = true;
    Timer.periodic(Duration(seconds: seconds), (t) {
      setState(() {
        timer = t;
        randomNote = Random().nextInt(6);
        randomType = Random().nextInt(6);
      });
    });
  }
}

And if you're going to do timer?.cancel(); make sure to set isTimerOn as false.

CodePudding user response:

The probably most elegant way to solve this problem is to disable the stop button till the start process is finished and disable the start button, till the process of the stop button is finished.

A explanation how a button can be disabled was already solved in this post -> How do I disable a Button in Flutter?

This way you can use the state of a bool which is changend when the timer is active and change the state of the bool when the timer stops.

  • Related