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

Flutter中如何捕获“Null check operator used on a null value”异常?

解决空检查CastError捕获并显示FlutterToast的问题

你原来的try-catch没抓到_CastError,核心原因是**_CastError属于Error类型,不是Exception**,而on Exception catch ()只会捕获Exception子类的异常,自然抓不到Error类的错误。

下面是具体的解决方法:

方法1:捕获所有异常和错误

直接用catch (e)可以捕获所有类型的异常(包括Exception和Error),也可以分开指定捕获Error和Exception:

Future addWidget(String path,String fileName,String fullName,String description,String now) async {
    try {
      await DataBase().addWidget(path, fileName, fullName, description, now);
      // 注意:如果DataBase().addWidget是异步方法,必须加await才能捕获内部抛出的异常
    } catch (e) { // 捕获所有Error和Exception
      Fluttertoast.showToast(
        msg: 'Oops something went wrong',
        gravity: ToastGravity.TOP,
        toastLength: Toast.LENGTH_SHORT,
        backgroundColor: Colors.grey[400],
        textColor: Colors.black,
      );
    }
  }

方法2:针对性捕获空检查CastError

如果只想捕获空检查导致的_CastError,可以单独指定类型:

Future addWidget(String path,String fileName,String fullName,String description,String now) async {
    try {
      await DataBase().addWidget(path, fileName, fullName, description, now);
    } on _CastError catch (e) { // 仅捕获空检查引发的CastError
      Fluttertoast.showToast(
        msg: '数据为空,操作失败',
        gravity: ToastGravity.TOP,
        toastLength: Toast.LENGTH_SHORT,
        backgroundColor: Colors.grey[400],
        textColor: Colors.black,
      );
    } catch (e) { // 兜底捕获其他异常/错误
      Fluttertoast.showToast(
        msg: 'Oops something went wrong',
        gravity: ToastGravity.TOP,
        toastLength: Toast.LENGTH_SHORT,
        backgroundColor: Colors.grey[400],
        textColor: Colors.black,
      );
    }
  }

额外提示

调试模式下Flutter默认会在控制台输出错误信息,若想完全屏蔽控制台的错误输出,可以在main方法里配置FlutterError.onError,但不建议调试时这么做,会影响问题排查:

void main() {
  FlutterError.onError = (details) {
    // 仅显示Toast,屏蔽控制台错误输出
    Fluttertoast.showToast(
      msg: 'Oops something went wrong',
      gravity: ToastGravity.TOP,
      toastLength: Toast.LENGTH_SHORT,
      backgroundColor: Colors.grey[400],
      textColor: Colors.black,
    );
    // 可添加判断,仅在发布模式屏蔽:if (!kDebugMode) ...
  };
  runApp(MyApp());
}

内容的提问来源于stack exchange,提问作者It'sPhil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:20:26