Search code examples
fluttertimepicker

The value extracted from showTimePicker Flutter


I created a showTimePicker and I changed the format in 24h, but when I am extracting the value in the ".then" future I get the time in 12h format. Can somebody tell me where is the issue? This is the code:

 void _presentTimePicker() {
showTimePicker(
    context: context,
    initialTime: TimeOfDay(
        hour: TimeOfDay.now().hour,
        minute: (TimeOfDay.now().minute - TimeOfDay.now().minute % 10 + 10)
            .toInt()),
    builder: (BuildContext context, Widget child) {
      return MediaQuery(
          data:
              MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
          child: child);
    }).then((value) {
  if (value == null) return;
  setState(() {
    time.text = TimeOfDay(
      hour: value.hour,
      minute: value.minute,
    ).format(context);
    print(time.text);
  });
});

}

the output is: 5:50 PM when I selected in picker 17:50


Solution

  • This issue is how you are changing the time of day back to a string. Try using this instead, so that you can override the default.

    localizations.formatTimeOfDay(TimeOfDay(
      hour: value.hour,
      minute: value.minute,
    ), alwaysUse24HourFormat: true);
    

    (The default is derived from MediaQuery - see here for more details of how.)