I'm trying to code a countdown timer showing the hours minutes and seconds remaining.
I've been trying to set the time to 24h60min60s first and it was working perfectly. But since I'm trying with 10hours it doesn't show 9h59min59s but 059h59min59s, I've been trying for hours to solve it but I don't understand how to do it as I've been starting coding really recently. I don't understand how to manage this error.
If you could bring me your help guys, It would be handsome.
class Page extends StatefulWidget {
const Page({super.key});
@override
State<Page> createState() => _PageState();
}
class _PageState extends State<Page> {
int seconds = 60;
int minutes = 60;
int hours = 10;
String secText = '00';
String minText = '00';
String hText = '10';
Timer? _timer;
@override
void initState() {
super.initState();
_handleTimer();
}
void _handleTimer() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
if (hours >= 10) {
hours--;
minutes--;
seconds--;
} else {
if (minutes == 60) {
minutes--;
}
if (minutes >= 60) {
minutes--;
seconds--;
} else {
if (seconds == 60) {
minutes--;
}
seconds--;
}
// if (minutes >= 1) {
//minutes--;
// seconds--;
//} else {
//if (seconds == 60) {
// minutes--;
// }
// seconds--;
// }
if (seconds > 9) {
secText = '$seconds';
} else {
if (seconds > 0) {
secText = '0$seconds';
} else {
seconds = 60;
secText = '00';
}
}
if (minutes > 9) {
minText = '$minutes';
} else {
if (minutes > 0) {
minText = '0$seconds';
} else {
secText = '00';
if (seconds == 60) {
_timer?.cancel();
}
}
}
if (hours > 9) {
hText = '$hours';
} else {
if (hours > 0) {
hText = '0$minutes';
}
}
}
});
});
}
The problem lies in this code part:
You pass minutes instead of hours. Change that to
hoursand everything should work as you expect.Basically you don't need to track seconds, minutes and hours separately. You can write a function, that will handle that for you: