0

I'm trying to get the following format from an int: ss:m (s = seconds, m = milliseconds) from a countdown timer. If there are minutes, the format should be mm:ss:m.

Here's my code:

final int currentTime = 100; // 10 seconds
final Duration duration = Duration(milliseconds: 100);
    Timer.periodic(duration, (Timer _timer) {
      if (currentTime <= 0) {
        _timer.cancel();
      } else {
        currentTime--;
        print(currentTime);
      }
});

I tried adding currentTime to a Duration as milliseconds but it didn't give me the desired results. What am I doing wrong and how can I get it to the correct format?

Jessica
  • 9,379
  • 14
  • 65
  • 136

2 Answers2

0

try Duration.toString() it'll give you a string formatted in your requirement more precisely

Duration(milliseconds:currentTime).toString()

and 100 millis is not 10 seconds

10000 millis is 10 seconds

Yadu
  • 2,979
  • 2
  • 12
  • 27
0

I have used the below method the get it in hh:mm:ss / mm:ss format, you can tweak to get in s:mm

String getTime(int milis) {
    Duration position = Duration(milliseconds: milis);
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(position.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(position.inSeconds.remainder(60));
    String time;
    if (twoDigits(position.inHours) == "00") {
      time = "$twoDigitMinutes:$twoDigitSeconds";
    } else {
      time = "${twoDigits(position.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
    }
    return time;
  }