Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 739
Jatin Pandey Avatar asked Aug 03 '20 04:08

Jatin Pandey


2 Answers

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;
  });
}
like image 133
Jatin Pandey Avatar answered Oct 12 '22 23:10

Jatin Pandey


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

like image 23
Zotov Avatar answered Oct 13 '22 00:10

Zotov