Home > Mobile >  Flutter Date Picker not working in the latest version
Flutter Date Picker not working in the latest version

Time:11-13

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

CodePudding user response:

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

CodePudding user response:

Make picked nullable by using "?"

final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2021, 1, 1),
        lastDate: DateTime(2022, 1, 1),
    );

CodePudding user response:

The return type from showDatePicker() is DateTime? ie it's nullable. Just remove the type:

final picked = await showDatePicker(
    context: context,
    initialDate: selectedDate,
    firstDate: DateTime(2021, 1, 1),
    lastDate: DateTime(2022, 1, 1),
);
  • Related