Flutter Date Picker 在最新版本中不起作用

Flutter Date Picker not working in the latest version

我正在开发一个 flutter 项目版本 2.2.3。我在旧版本中有相同的代码集。它工作正常。但在最新版本中,日期选择器不起作用。

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),
    );

我收到以下错误

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(

这是我的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

使用“?”使选择的可为空

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

showDatePicker() 中的 return 类型是 DateTime? 即它可以为空。 只需删除类型:

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

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.

当您未选择就关闭对话框时,showDatePicker 可能不会 return 日期。让它像

一样可以为空
 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),
    );
  }

更多关于showDatePicker

    DateTime _date = DateTime.now();
    
    
    
     TextFormField(
       readOnly: true,
       controller: dateCtl,
       decoration: InputDecoration(
       labelText: 'Date',
       ),
       onTap: () async {
       await showDatePicker(
       context: context,
       initialDate: DateTime.now(),
       firstDate: DateTime(2015),
       lastDate: DateTime(2025),
       ).then((selectedDate) {
       if (selectedDate != null) {
       dateCtl.text = DateFormat('yyyy-MM-dd')
       .format(selectedDate);
        }
        });
        },
        validator: (value) {
        if (value == null || value.isEmpty) {
        return 'Please enter date.';
        }
        return null;
        },
        ),

Do have a lot at this code once, it will solve your issue