fluttertime-format

Flutter display time in Text widget


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.


Solution

  • 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.