How to show the flutter timepicker in 12 hours format with AM PM selector

Viewed 9899

I want to use the Flutter timepicker in 12 hour format with AM/PM selector, but Flutter only shows me the 24 hours format.

I want to get this format: enter image description here

But flutter only shows me this format: enter image description here

This is my code:

_selectTime(BuildContext context) async {
  TimeOfDay picked = await showTimePicker(
    context: context,
    initialTime: TimeOfDay(hour: 12, minute: 00),
    builder: (BuildContext context, Widget child) {
      return MediaQuery(
        data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
        child: child,
      );
    },
  );
}
4 Answers

This should show you what you want

RaisedButton(
  child: Text('Show Time Picker'),
  onPressed: () async => await showTimePicker(
    context: context,
    builder: (BuildContext context, Widget child) {
      return MediaQuery(
        data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
        child: child,
      );
    },
  ),
),

just use format() method to get AM,PM what you required.

final TimeOfDay picked = await showTimePicker(
  context: context,
  initialTime: timeStart,
);
print(picked.format(context));    // 8:15 PM

Use can this lib Flutter DatePicker

Code to show 12 hours format with AM/PM:

onTap: (){
    DatePicker.showTime12hPicker(context,
        showTitleActions: true,
        onConfirm: (date) {
          _endTimeController.text = DateFormat.jm().format(date);
        }, locale: LocaleType.en);
  },

And see result below:

enter image description here

Below snippet, I found form Flutter Github Issues

await showTimePicker(
          initialTime: TimeOfDay.now(),
          context: context,
          builder: (context, child) {
            final Widget mediaQueryWrapper = MediaQuery(
              data: MediaQuery.of(context).copyWith(
                alwaysUse24HourFormat: false,
              ),
              child: child,
            );
            // A hack to use the es_US dateTimeFormat value.
            if (Localizations.localeOf(context).languageCode == 'es') {
              return Localizations.override(
                context: context,
                locale: Locale('es', 'US'),
                child: mediaQueryWrapper,
              );
            }
            return mediaQueryWrapper;
          },
        );

Time Picker is picking format based on locale. Above code is tweaking country of Locale to US because US has 12 hours of time format. Instead of "es" use language code in which you are getting problem.

All credit goes to person who posted solution in above mentioned link. I am reposting it here so, people can find that solution easily.

Related