'How to change time picker's format independent of language
Anyone knows how I can use the AM/PM format of the time picker in any language?
The app has english & romanian languages, when in romanian the time picker it uses the 24 hour format, though I need AM/PM.
I didn't found any way to set a locale to it, so I am a bit stuck.
Solution 1:[1]
Since Filip didn't edit his answer, I will put an answer myself with the solution.
showTimePicker requires both setting alwaysUse24HourFormat to true and changing the locale to en-US in the builder method of the function.
Doing one without the either doesn't do anything.
So, the proper solution is:
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
builder: (BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
child: Localizations.override(
context: context,
locale: const Locale('en', 'US'),
child: child!,
),
),
);
There is an open Github issue aswell, for this issue.
Solution 2:[2]
The TimePickerDialog gets its format from MediaQuery.of(context).
As shown in the documentation for showTimePicker you can pass a builder to showTimePicker to force 24 hour format.
You can use the current Locale to pick the time format.
final time = showTimePicker(
context: context,
initialTime: const TimeOfDay(hour: 10, minute: 47),
builder: (BuildContext context, Widget? child) {
Locale locale = Localizations.localeOf(context);
final force24HourFormat = locale.countryCode == 'RO';
return MediaQuery(
data: MediaQuery.of(context).copyWith(
alwaysUse24HourFormat: force24HourFormat,
),
child: child!,
);
},
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | adi |
| Solution 2 | Filip Marko |
