Ad

Flutter Date Picker Not Working In The Latest Version

i am working on a flutter project version 2.2.3. I have same set of codes in old version. it was working fine. but in the latest version datepicker is not working.

DateTime selectedDate = DateTime.now();

Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2021, 1, 1),
        lastDate: DateTime(2022, 1, 1),
    );

i am getting the following error

Error: A value of type 'DateTime?' can't be assigned to a variable of type 'DateTime' because 'DateTime?' is nullable and 'DateTime' isn't.
 - 'DateTime' is from 'dart:core'.
    final DateTime picked = await showDatePicker(

here is my flutter doctor -v

 Flutter (Channel stable, 2.2.3, on macOS 11.3.1 20E241 darwin-x64, locale en-IN)
• Flutter version 2.2.3 at /Users/user1/fvm/versions/2.2.3
• Framework revision f4abaa0735 (4 months ago), 2021-07-01 12:46:11 -0700
• Engine revision 241c87ad80
• Dart version 2.13.4
Ad

Answer

The returned Future resolves to the date selected by the user when the user confirms the dialog. If the user cancels the dialog, null is returned.

It is possible case that showDatePicker will not return date when you close the dialog without selecting. Make it like nullable like

 Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(2021, 1, 1),
      lastDate: DateTime(2022, 1, 1),
    );
  }

More about showDatePicker

Ad
source: stackoverflow.com
Ad