When I add date picker then show 'Non-nullable instance field 'selectedDate' must be initialized. ' error
DateTime selectedDate;
void showDatePicker() {
showCupertinoModalPopup(
context: context,
builder: (BuildContext builder) {
return Container(
height: MediaQuery.of(context).copyWith().size.height * 0.25,
color: Colors.white,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
onDateTimeChanged: (value) {
if (value != null && value != selectedDate)
setState(() {
selectedDate = value;
});
},
initialDateTime: DateTime.now(),
minimumYear: 2019,
maximumYear: 2021,
),
);
});
}
CodePudding user response:
If you want init variable selectedDate
later, use late:
late DateTime selectedDate;
or if you want to make selectedDate
can have a null value then initiate it like this:
DateTime? selectedDate;
"?" after data type mean nullable.
CodePudding user response:
You declared selectedDate
as non-nullable, which means it can never be null. When you do that you need to give it an initial value. The solution is to make it nullable by adding a ?
DateTime? selectedDate;