Search code examples
flutterdarttimepicker

add time picker to flutter code causes error


I use below code to add time picker:

final TimeOfDay newTime = await showTimePicker(
  context: context,
  initialTime: TimeOfDay(hour: 7, minute: 15),
);

But I give below error:

A value of type 'TimeOfDay?' can't be assigned to a variable of type 'TimeOfDay'. Try changing the type of the variable, or casting the right-hand type to 'TimeOfDay'


Solution

  • Simply change to:

    final TimeOfDay? newTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay(hour: 7, minute: 15),
    );
    

    Then you may want to unwrap the optional result:

    if (newTime != null) {
      // do stuff with newTime
    }