LostTexan
LostTexan

Reputation: 891

Time picker not returning value in flutter app

I am using flutter_datetime_picker: ^1.5.1 to be able to pick dates and time for scheduled events.

Here is the screen I am using:

enter image description here

The Start Time field is where I am having problems. When I click in the field the Time Picker is displayed. Once I select a time and click "Ok" the text field does not get the selected time.

Here is the code I have inside the onTap: property:

onTap: () async {
                    TimeOfDay _timePicked = await (showTimePicker(
                        context: context,
                        initialTime: new TimeOfDay.now()) as FutureOr<TimeOfDay>);
                    if (_timePicked != null) {
                      _dt = DateTime(_selectedDate!.year, _selectedDate!.month, _selectedDate!.day, _timePicked.hour, _timePicked.minute);
                      setState(() {
                        eventStartTimeController.text = DateFormat('h:mm a').format(_dt); //_timePicked.format(context);
                        eventProvider.changeeventstarttime(_dt);
                      });
                    }
                  },

When debugging, the execution does not stop at any break point set after I have selected a time. What is going on here?

I have upgraded to Dart 2, null-safety so I don't know if this has anything to do with the code.

Upvotes: 1

Views: 1698

Answers (2)

Aizaz ahmad
Aizaz ahmad

Reputation: 61

You can change your code to this. it will work.

TimeOfDay _timePicked = await (showTimePicker(
                    context: context,
                    initialTime: new TimeOfDay.now()) as FutureOr<TimeOfDay>);
                if (_timePicked != null) {
                  _dt = DateTime(_selectedDate!.year, _selectedDate!.month, _selectedDate!.day, _timePicked.hour, _timePicked.minute);
                  setState(() {
                     final localizations = MaterialLocalizations.of(context);
                     final formattedTimeOfDay = localizations.formatTimeOfDay(_timePicked!,alwaysUse24HourFormat: false);
                    eventStartTimeController.text = formattedTimeOfDay;  
                    eventProvider.changeeventstarttime(_dt);
                  });

 

Upvotes: 0

Vadim Popov
Vadim Popov

Reputation: 772

Looks like the error is here

... as FutureOr);

Try this one, it works fine

final TimeOfDay _timePicked = await showTimePicker(
  context: context,
  initialTime: TimeOfDay.now(),
);
 if (_timePicked != null) {
  _dt = DateTime(
  _selectedDate.year,
  _selectedDate.month,
  _selectedDate.day,
  _timePicked.hour,
  _timePicked.minute,
 );
 setState(() {
  eventStartTimeController.text = DateFormat('h:mm a')
   .format(_dt); //_timePicked.format(context);
  eventProvider.changeeventstarttime(_dt);
 });
}

Upvotes: 1

Related Questions