2

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 2

2

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"
Sign up to request clarification or add additional context in comments.

4 Comments

This a dart native feature, you don't have to import anything. @Mason
I uploaded an example main.dart here: gist.github.com/EdYuTo/7cf2f24b1fb1caefaffa3b1f714ccd5d
Here is my code. For some reason, there is an error saying The method 'formatMinute' isn't defined for the class 'int'. This is only specific to my coding, not yours. Do you know why? If you don't, that's fine. Thank you so much for helping me.
just updated my answer with a quick explanation. Also, you don't need to import my custom 'Time' class, that was just an example. But I hope it works now, @Mason
1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.