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.
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;
});
}
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,
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With