I wrote a code that counts down from 240 seconds to 0 second in the Flutter app.
But only seconds come out here.
All I want is to have minutes and seconds represented
int _Counter = 240;
late Timer _timer;
void startTimer(){
_timer = Timer.periodic(Duration(seconds: 1), (timer){
if(_Counter > 0){
setState(() {
_Counter--;
});
}else{
_timer.cancel();
}
});
}
ex)
- 240 = 04:00
- 200 = 03:20
- 60 = 01:00
- 10 = 00:10
- 0 = 00:00
I don’t know how to solve it.
Can someone give me a solution or tell me how?
Thank you.
3
Answers
To calculate the minutes, you must divide the seconds by 60. To calculate the remaining seconds, you must subtract the minutes from the seconds. You can then use padLeft to place a zero in front of a number if it only has one digit.
You want to manage it after counter decrementing, look at bellow,
In this modification,
timerText
is now a function that returns a formatted string representing the remaining time. Inside thestartTimer
function, we calltimerText()
immediately after decrementing the counter within thesetState
callback. This ensures that the displayed time gets updated each time the counter decrements.Package intl has DateFormat. You can turn DateTime into any format you want.