What is the correct way to add time picker in flutter app?

9,398

Solution 1

First declare this variable at the class level,

TimeOfDay selectedTime = TimeOfDay.now();

and then call this method -

Future<void> _selectTime(BuildContext context) async {
final TimeOfDay picked_s = await showTimePicker(
    context: context,
    initialTime: selectedTime, builder: (BuildContext context, Widget child) {
       return MediaQuery(
         data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
        child: child,
      );});

if (picked_s != null && picked_s != selectedTime )
  setState(() {
    selectedTime = picked_s;
  });
}

Solution 2

This code will shows a dialog containing a material design time picker.

Note that a showTimePicker is Future. So, you need to use await to get a time.

TimeOfDay initialTime = TimeOfDay.now();
TimeOfDay pickedTime = await showTimePicker(
    context: context,
    initialTime: initialTime,
);

Material Design Time Picker Image

Also you could customize your time picker using builder property inside the showTimePicker

TimeOfDay initialTime = TimeOfDay.now();
TimeOfDay pickedTime = await showTimePicker(
    context: context,
    initialTime: initialTime,
    builder: (BuildContext context, Widget child) {
      return Directionality(
        textDirection: TextDirection.rtl,
        child: child,
      );
    },
);

You can learn more about it on a official documentation here

Share:
9,398
Jatin Pandey
Author by

Jatin Pandey

Updated on December 23, 2022

Comments

  • Jatin Pandey
    Jatin Pandey over 1 year

    In my app, the user needs to select a time manually for a task, but I do not know what is the correct way to use time picker in flutter app and select the time(of a day) manually by the user.

  • Balaji
    Balaji about 3 years
    What about iOS? I mean cupertino style?
  • Elmar
    Elmar almost 2 years
    Works with null safety in 2022: Just change this part: final TimeOfDay picked_s -----> final TimeOfDay? picked_s