I have created a quiz app using Flutter and Laravel, Everything is working fine except for Timer.
The Time is reduced multiple times for question no. as
Reduces means if I given 60 seconds for each question then in the first que. it is okay but in 2nd ques. it starting from 60 the 58 the 56 then 54 sec..
and in 3rd, it starts from 60 then 57 then 54.. this way.
- first question timer reduces 1 second.
- in the second question, it reduces to 2 seconds.
- in the third question it reduces 3 seconds and
- after 10 questions it only is there for a few seconds
int timer = 60;
String showtimer = "60";
bool canceltimer = false;
Here is the timer function
void startTimer() async {
const oneSec = Duration(seconds: 1);
Timer.periodic(oneSec, (Timer t) {
setState(() {
if (timer < 1) {
t.cancel();
this.nextQuestion(context);
} else if (canceltimer == true) {
t.cancel();
} else {
timer = timer - 1;
}
showtimer = timer.toString();
});
});
}
And in the nextQuestion method, I am further calling showtimer function
CodePudding user response:
This is a pretty classic symptom of accumulating multiple periodic Timer
s: initially you'll see your callback triggered once per period, but eventually you'll see it called twice per period, and later three times per period, and so on. This is easy to verify by adding debugPrint
statements to your Timer
callback.
Skimming over your code, when someone answers a question, verifyAndNext
will start a new periodic Timer
for the next question without cancelling the previous Timer
. As written, your code can't cancel the previous Timer
because you've made each periodic Timer
responsible for cancelling itself.
You want an invariant that there should be at most one periodic Timer
active at any time. You should enforce that. One typical pattern is to save the periodic Timer
somewhere (such as to a member variable) and to check whether a Timer
already exists before creating a new one. This would provide a strong guarantee that you never create multiple periodic Timer
s that are simultaneously active:
Timer? periodicTimer;
void startTimer() async {
const oneSec = Duration(seconds: 1);
periodicTimer?.cancel();
periodicTimer = Timer.periodic(oneSec, (Timer t) {
...
});
}
CodePudding user response:
check this, your initial time is int timer = 60;
so after first question u'll update timer = 60
,
In updated timer you have to do timer = 60 - i
i is for question number like i = 1,2,3 in this scenario timer will reduces 1 second and depend on ur question number. hope this logic will use for you.