You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter DateTime选择器空检查运算符使用错误求助

解决「Null check operator used on a null value」错误——日期选择与Firestore查询问题

错误原因

你在showMonthYearPicker的builder回调里直接调用selected!.year和selected!.month,但此时selected还未被赋值。selected = await showMonthYearPicker(...)是异步操作,只有用户选择日期并关闭弹窗后,selected才会被赋值;而builder是弹窗初始化渲染时就执行的,这时候selected还是null,用!强制解包必然触发空指针错误。

解决方案

  1. 移除builder内的print语句,不要在弹窗渲染阶段访问未赋值的selected
  2. 在await获取到selected后,再进行非空判断并使用日期数据,比如传入Firestore查询

修改后的代码示例

ElevatedButton(
  style: ElevatedButton.styleFrom(
      shape: StadiumBorder(),
      backgroundColor: Palette.primaryColor),
  onPressed: () async {
    selected = await showMonthYearPicker(
      context: navigatorKey.currentState!.overlay!.context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2022),
      lastDate: DateTime.now(),
      builder: (context, child) {
        // 此处不要访问selected,弹窗渲染时它还未被赋值
        return Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 50.0),
              child: Container(
                height: 500,
                width: 800,
                child: child,
              ),
            ),
          ],
        );
      },
    );
    // 弹窗关闭后,判断selected非空再使用
    if (selected != null) {
      print(selected!.year);
      print(selected!.month);
      // 在这里执行Firestore查询逻辑
      // 示例:FirebaseFirestore.instance.collection('your_collection')
      //       .where('year', isEqualTo: selected!.year)
      //       .where('month', isEqualTo: selected!.month)
      //       .get();
    }
  },
  child: Center(child: Text('Choisir mois'))),

额外提示

因为selected是DateTime?类型,必须先通过if (selected != null)做非空校验,避免用户未选择日期直接关闭弹窗时再次触发空指针错误。

内容的提问来源于stack exchange,提问作者Fedy Belaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:50:21