计时器10点后不再回到09

问题描述 投票:0回答:1

我正在尝试编写一个倒计时器来显示剩余的小时、分钟和秒数。

我一直尝试先将时间设置为 24 小时 60 分 60 秒,效果很好。但由于我尝试使用 10 小时,它不显示 9h59min59s,而是显示 059h59min59s,我已经尝试了几个小时来解决它,但我不明白如何做到这一点,因为我最近才开始编码。我不明白如何处理这个错误。

如果你能给我带来你的帮助,那就太好了。

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';
            }
          }
        }
      });
    });
  }
flutter dart timer countdowntimer
1个回答
0
投票

问题出在这段代码部分:

if (hours > 9) {
            hText = '$hours';
          } else {
            if (hours > 0) {
              hText = '0$minutes';
            }
          }

您度过了几分钟而不是几个小时。 将其更改为

hours
,一切都会如您所愿。

基本上你不需要分别跟踪秒、分钟和小时。您可以编写一个函数来为您处理这个问题:

String _formatTime(int time) {
  return time < 10 ? '0$time' : '$time';
}
© www.soinside.com 2019 - 2024. All rights reserved.