You need to enable JavaScript to run this app. Flutter使用Provider实现购物车加购时在null上调用containsKey报错如何修复
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用Provider实现购物车加购时在null上调用containsKey报错如何修复

故障现象

开发电商类Flutter应用,采用Provider实现购物车加购逻辑,flutter doctor检测结果全部正常,仅在点击加购按钮时触发运行时异常,报错信息如下:

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'containsKey' was called on null.
Receiver: null
Tried calling: containsKey("p1")
异常触发栈:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 Cart.addItem
package:shop_stop/…/components/cart.dart:33
#2 _ProductItemState.build.
package:shop_stop/widgets/product_item.dart:80

问题根因

排查对应业务代码后,定位到异常触发点为Cart类的私有购物车字段未初始化,运行时该字段默认值为null:

class Cart with ChangeNotifier {
  // 仅声明Map类型,未赋初始值,实际值为null
  Map<String, CartItem> _items;
}

调用addItem方法时,第一行逻辑就执行_items.containsKey(productId),等价于在null对象上调用实例方法,直接触发NoSuchMethodError。后续如果直接访问itemCount getter,也会因为读取空对象的length属性触发同类异常。
该问题和Provider配置、商品页组件逻辑无关,异常栈的调用路径已经明确指向Cart类内部的空引用问题。

修复方案

仅需给_items字段补充空Map初始值,原有业务逻辑无需调整,修改后的Cart类核心实现:

class Cart with ChangeNotifier {
  // 初始化空购物车Map,消除空引用风险
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {..._items};
  }

  int get itemCount {
    return _items.length;
  }

  void addItem(
    String productId,
    double price,
    String title,
  ) {
    if (_items.containsKey(productId)) {
      // 购物车已存在同商品,累加购买数量
      _items.update(
        productId,
        (existingCartItem) => CartItem(
          id: existingCartItem.id,
          title: existingCartItem.title,
          price: existingCartItem.price,
          quantity: existingCartItem.quantity + 1,
        ),
      );
    } else {
      // 新商品首次加入购物车
      _items.putIfAbsent(
        productId,
        () => CartItem(
          id: DateTime.now().toString(),
          title: title,
          price: price,
          quantity: 1,
        ),
      );
    }
    notifyListeners();
  }
}

完成修改后重新运行应用,加购功能即可正常工作。


内容的提问来源于stack exchange,提问作者Ameen Ul Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 20:36:03