How do you print the result of a String function in Flutter?

Viewed 2993

This is my code:

String formatMinute() {
    if (int.parse('${_time.minute}') < 10) {
      String newMin = '${_time.minute}' + '0';
      return newMin;
    }
  }

I would like the result of formatMinute() to be in a statefulWidget. Here is my code in the statefulWidget.

Text('Time selected: ${_time.hour}:${_time.minute}'),

I would like "${_time.minute}" to be replaced with the result of formatMinute(). Is this possible? Thanks for your time and help!

2 Answers

You should try using an extension method! (https://dart.dev/guides/language/extension-methods)

Keep in mind that TimeOfDay _time = new TimeOfDay.now() will have the properties hour and minute as int, so your extension method should also be on an int:

extension NumberFormat on int {
  String formatMinute() {
    if (this < 10) {
      String newMin = '0' + this.toString();
      return newMin;
    }
    return this.toString();
  }
}

And then, this should go inside your widget:

Text('Time selected: ${_time.hour}:${_time.minute.formatMinute()}')

Notice that the extension method is something like a class, so you need to declare it outside your widget class.

You should update your pubspec to remove any warning too:

 environment:
  sdk: ">=2.6.0 <3.0.0"

In Dart, you can put any code including function calls inside string interpolation. So this is perfectly valid:

Text('Time selected: ${_time.hour}:${formatMinute()}')

Also note that formatMinute implementation could simplified:

String formatMinute() => _time.minute.padLeft(2, '0');
Related