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

Flutter调用Provider触发_CastError空检查运算符空值错误如何解决

问题描述

在Flutter开发过程中从服务端拉取数据后,调用通知器弹出通知时,调用Provider会抛出_CastError错误,错误信息为*「Null check operator used on a null value」*。
相关实现代码如下:

class OrderBranches with ChangeNotifier {
  static List<OrderBranch> _items = [];
  static List<OrderBranch> _soldOrders = [];

  List<OrderBranch> get items {
    return [..._items];
  }

  Future<void> fetchOrderBranches() async {
    try {
      var url = basicURL + 'orderBranch/';
      // print('url');
      // print(url);
      final responseData =
          await MyRequest.callGet(url, headers, 'fetchOrderBranches');
      // final responseData = json.decode(response.body);
      // _items.clear();
      responseData.forEach((item) {
        addOrderBranchAndDependents(item);
      });
      notifyListeners();
    } catch (e) {
      print('Error');
      print(e);
    }
  }


  static void addOrderBranchAndDependents(Map<String, dynamic> localMap) {
    OrderBranch orderBranch = await classMapToObj(orderBranchData);
    bool found = false;
    // if order status is opened and it is notifiable then show notification
    bool branchNotificationFlag = orderBranchData['Branch_Notification'];

    String orderStatus = orderBranchData['Order']['OrderStatus']['Name'];
    if (orderBranch.orderBranchStatusName == 'Pending' &&
        orderStatus == 'Opened' &&
        branchNotificationFlag == true) {
      await changeBranchNotificationFlag(orderBranch.id);
     
        var notifierProvider =
            Provider.of<Notifier>(confContext, listen: false);
        notifyOrderNotification(
            notifierProvider,
            orderBranch.slug,
            'New order from Ommino',
            'Tap here to get details of your new order, by Ommino');
  }

}
错误原因
  • 方法入参为localMap,但代码内部直接使用未定义的orderBranchData变量,读取到的值为null,调用null的属性会触发空校验报错
  • addOrderBranchAndDependents为静态方法,内部使用的全局confContext未赋值、或者已经失效(对应页面销毁),Provider依赖有效上下文查找实例,上下文为null时触发空校验报错
  • 方法内使用了await关键字,但方法未标记为async,执行时序异常也会导致上下文失效、变量为空
修复方案
  1. 移除addOrderBranchAndDependents的static修饰符,给方法补全async标记,添加上下文入参,同时将代码里的orderBranchData替换为入参localMap:
Future<void> addOrderBranchAndDependents(Map<String, dynamic> localMap, BuildContext context) async {
  OrderBranch orderBranch = await classMapToObj(localMap);
  bool found = false;
  // if order status is opened and it is notifiable then show notification
  bool branchNotificationFlag = localMap['Branch_Notification'];

  String orderStatus = localMap['Order']['OrderStatus']['Name'];
  if (orderBranch.orderBranchStatusName == 'Pending' &&
      orderStatus == 'Opened' &&
      branchNotificationFlag == true) {
    await changeBranchNotificationFlag(orderBranch.id);
    // 先判断上下文是否有效
    if (context.mounted) {
      var notifierProvider = Provider.of<Notifier>(context, listen: false);
      notifyOrderNotification(
          notifierProvider,
          orderBranch.slug,
          'New order from Ommino',
          'Tap here to get details of your new order, by Ommino');
    }
  }
}
  1. 修改fetchOrderBranches方法,添加上下文入参,透传给addOrderBranchAndDependents:
Future<void> fetchOrderBranches(BuildContext context) async {
  try {
    var url = basicURL + 'orderBranch/';
    final responseData =
        await MyRequest.callGet(url, headers, 'fetchOrderBranches');
    // 改用for循环处理异步逻辑,forEach不支持await
    for (var item in responseData) {
      await addOrderBranchAndDependents(item, context);
    }
    notifyListeners();
  } catch (e) {
    print('Error');
    print(e);
  }
}
  1. 在Widget层调用fetchOrderBranches时,传入当前页面的有效BuildContext即可。

内容的提问来源于stack exchange,提问作者Shabber Naqvi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:06:00