【问题标题】:error : I get error ' Unexpected null value' when I run app错误:运行应用程序时出现错误“意外的空值”
【发布时间】:2022-01-21 14:20:08
【问题描述】:

1.这是第一个代码:

 DateTime? _selectedTime;
  void _datePicker(BuildContext con2) {
    showDatePicker(
      initialDate: DateTime.utc(2021, 12, 21),
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      context: con2,
      // ignore: non_constant_identifier_names
    ).then((UserSelect) {
      if (UserSelect == null) {
        return;
      }
      setState(() {
        UserSelect = _selectedTime;
      });
    });
  }

2.这是第二个:

body: Container(
          color: Colors.black,
          height: double.infinity,
          child: Center(
            child: ElevatedButton(
              onPressed: () {
                _datePicker(context);
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.purple)),
              child: Text(
                '${DateFormat('yyyy/MM/dd').format(_selectedTime!)}',

【问题讨论】:

    标签: dart flutter-test dart-null-safety


    【解决方案1】:

    我认为您没有正确使用它。 showDatePicker 返回一个 Future 值。看看这个,也许这会指导你; What is the correct way to add date picker in flutter app?

    【讨论】:

      【解决方案2】:

      你犯了很多错误,你犯的第一个错误 DateTime 支持 null-safty,但是 .form、initialDate、firstDate 和 lastDate 没有使用 null 安全性。 第二个错误是你的 _datePicker 不支持异步,因为当用户选择时间时他们需要一些时间才能选择。

        DateTime _selectedTime = DateTime.now();
        void _datePicker(BuildContext con2) async {
          final DateTime? picked = await showDatePicker(
            context: con2,
            initialDate: DateTime.utc(2021, 12, 1), // Refer step 1
            firstDate: DateTime(2000),
            lastDate: DateTime.now(),
          ).then((UserSelect) {
            if (UserSelect == null) {
              return;
            }
            setState(() {
               _selectedTime = UserSelect;
            });
          });
        }
      

      您添加的第三个错误!在 _seletedTime

      ElevatedButton(
                  onPressed: () => _datePicker(context)
                  ,
                  child: Text(
                    '${DateFormat('yyyy/MM/dd').format(_selectedTime)}',),
      

      【讨论】:

        猜你喜欢
        • 2018-03-26
        • 2013-07-07
        • 2021-04-01
        • 2014-05-14
        • 2018-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多