I have this code to display DatePicker
and after which TimePicker
will come up and I will retrive all the seleted values and it was working perfectly fine until I migrated to null safety by creating a flutter project and coping all my code to the new project and also and doing a few "pub get, Upgrade"
Below is my code:
//Select Date and Time Widget
Future _selectDayAndTimeL(BuildContext context) async {
DateTime _selectedDay = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) => child);
TimeOfDay _selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (_selectedDay != null && _selectedTime != null) {
//a little check
}
setState(() {
selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
// _selectedDate = _selectedDay;
});
// print('...');
}
Now I got this error:
A value of type 'DateTime?' can't be assigned to a variable of type 'DateTime'.
A value of type 'TimeOfDay?' can't be assigned to a variable of type 'TimeOfDay'.
Check the image to see... I have gone through the questions I saw on almost same issue but it did not solve my problem
How do i solve this error
CodePudding user response:
showDatePicker returns Future DateTime?
:
Future<DateTime?> showDatePicker(...)
So, you need to change the following:
DateTime _selectedDay = await showDatePicker(...)
to:
DateTime? _selectedDay = await showDatePicker(...)
showTimePicker returns Future TimeOfDay?
:
Future<TimeOfDay?> showTimePicker(...)
So, change the following:
TimeOfDay _selectedTime = await showTimePicker(...);
to:
TimeOfDay? _selectedTime = await showTimePicker(...);
CodePudding user response:
Either null safe variable like TimeOfDay?
, or you can get the value at risk with (await showTimePicker(...))!