Search code examples
androidiosflutterdartflutter-layout

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.


Solution

  • 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? pickedTime = await showTimePicker(
        context: context,
        initialTime: selectedTime, builder: (BuildContext context, Widget child) {
           return MediaQuery(
             data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: false),
            child: child,
          );});
    
    if (pickedTime != null && pickedTime != selectedTime )
      setState(() {
        selectedTime = pickedTime;
      });
    }