首页 > 解决方案 > 我想将颤振计时器输出转换为 MM:SS 格式

问题描述

所以下面是我的计时器功能及其输出(都在同一页面内),我想知道如何将输出更改为分钟和秒。按照目前的情况,只需几秒钟。

class _TimerPageState extends State<TimerPage> {
  int _counter = 0;
  Timer _timer;
  bool _vibrationActive = false;

  void _startTimer() {
    _counter = Duration(minutes: 25).inMinutes;
    if (_timer != null) {
      _timer.cancel();
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_counter > 0) {
          _counter--;
        } else {
          _timer.cancel();
          vibrate();
          print(
              "I'm picking up good vibrations"); //test print to chceck if method gets past vibartion
        } //meaning that vibration function is called and working
      });
    });
  }

这是输出的地方

Widget _buildVerticalLayout(_counter, _startTimer, _pauseTimer) {
  return Scaffold(
    body: Padding(
      padding: EdgeInsets.symmetric(horizontal: 40.0, vertical: 60.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Text(
            'Pomo Timer',
            style: TextStyle(
                color: Colors.black,
                fontSize: 40.0,
                fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 140.0),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              (_counter > 0) ? Text("") : Text("5 minute break!",
                      style: TextStyle(
                        color: Colors.green,
                        fontWeight: FontWeight.bold,
                        fontSize: 48,
                      ),
                    ),
              Text(
                '$_counter',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 48,
                ),
              ),
              ElevatedButton(
                onPressed: () => _startTimer(),
                child: Text("Pomo Start"),
              ),
              ElevatedButton(
                onPressed: () {
                  _pauseTimer();
                },
                child: Text("Pomo Pasue"),
              ),
            ],
          ),
        ],
      ),
    ),
  );
}

根据我到目前为止所读的所有内容,我只是不知所措,我想我只是看得太仔细了。我希望这不仅仅是一个重复的问题,我会浪费时间。为回答的人干杯!

标签: flutterdart

解决方案


正如@mkobuolys 指出的那样,您将 25 分钟的持续时间转换为 25 的整数,然后每秒减去一次。所以我假设您打算将其转换为秒(您可以只做分钟*60)。

为了提供一个替代方案,一个自己处理这个问题的简单方法是使用内置dart:math函数和一些简单的数学:

'${(seconds/60).floor()}:'+'${seconds%60}'.padLeft(2, '0')

或者,如果您想要分钟部分的尾随零:

'${(seconds/60).floor()}'.padLeft(2, '0')+':'+'${seconds%60}'.padLeft(2, '0')

您可以通过将秒除以 60 ( seconds/60) 来获得分钟,然后使用floor删除余数。然后,您可以通过使用模运算符 ( seconds%60) 获取先前丢弃的余数来获得秒数。最后,padLeft如果数字是单个数字,您可以使用提供尾随零。


推荐阅读