skip to Main Content

I want to display a duration in format 00:00:00 with it adding 0 when needed so that for exemple I’d have 04:07:32 and not 4:7:32. I’m not familiar with flutter so I’m not sure what to do.

Text(
                  "temps : 0$hours:0$minutes:0$seconds",
                  style: const TextStyle(
                    fontSize: 24,
                  ),
                ) ,

this is my code. obviously the ‘0’ before displaying the variable isn’t working because while I do get the 04:07 to display as soon as it gets to the double digits it become 013:029 if you see what I mean. I could use a if to tell if one of the variable is in the single digits but I’m asking here hoping that there’s an easier solution.

2

Answers


  1. You can use padLeft like this:

    Text(
    "temps : ${hours.padLeft(2, "0")}:${minutes..padLeft(2, "0")}:${seconds.padLeft(2, "0")}",
    style: const TextStyle(
              fontSize: 24,
        ),
    ) ,
    

    The details of the method padLeft can be found here

    Pads this string on the left if it is shorter than width.

    Login or Signup to reply.
  2. As your duration will not be negative (I assume) you can use .padLeft(2, '0')
    This adds ‘0’ to the left of your string until it is 2 long.

    Text("temps : ${hours.padLeft(2, "0")}:${minutes.padLeft(2,"0")}:${seconds.padLeft(2, "0")}",
    style: const TextStyle(
          fontSize: 24,
        ),
    ),
    

    If you think you might deal with negative numbers at any point then take a look at NumberFormat from import 'package:intl/intl.dart';. It’s also simple.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search