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

Flutter购物车页面报错:type 'Null' is not a subtype of type 'String'

Flutter购物车列表加载失败问题解决

问题现象

购物车页面无法显示列表,报错type 'Null' is not a subtype of type 'String',定位到cartListOfCurrentUser.add(Cart.fromJson(eachCurrentUserCartData))行出错。注释该行后能正常打印接口返回数据,但无法填充列表。

错误原因

Cart.fromJson方法中直接使用int.parse、double.parse以及toString()处理接口返回字段,未考虑字段为null的场景:

  • 当接口返回的数字字段(如cart_id、item_rating)为null时,int.parse(null)或double.parse(null)会抛出类型错误,因为parse方法要求参数为String类型,null不符合要求。
  • 当数组类型字段(如item_tags)为null时,调用toString()会将null转为字符串"null",拆分后得到["null"],不符合预期,甚至可能引发后续错误。

解决方案

修改Cart类的fromJson工厂方法,对每个字段做null安全处理:

  1. 使用int.tryParse/double.tryParse替代int.parse/double.parse,解析失败时返回null,匹配模型中的可空字段定义。
  2. 对数组类型字段先判断是否为null,再执行拆分操作,避免在null对象上调用方法。
  3. 字符串类型字段直接返回null,或根据业务需求提供默认值。

修改后的Cart模型代码

class Cart {
  int? cart_id;
  int? user_id;
  int? item_id;
  int? cart_quantity;
  String? cart_color;
  String? cart_size;
  String? item_name;
  double? item_rating;
  List<String>? item_tags;
  double? item_price;
  List<String>? item_color;
  List<String>? item_size;
  String? item_desc;
  String? item_image;

  Cart({
    this.cart_id,
    this.user_id,
    this.item_id,
    this.cart_quantity,
    this.cart_color,
    this.cart_size,
    this.item_name,
    this.item_rating,
    this.item_tags,
    this.item_price,
    this.item_color,
    this.item_size,
    this.item_image,
    this.item_desc,
  });

  factory Cart.fromJson(Map<String, dynamic> json) => Cart(
        cart_id: int.tryParse(json['cart_id'].toString()),
        user_id: int.tryParse(json['user_id'].toString()),
        item_id: int.tryParse(json['item_id'].toString()),
        cart_quantity: int.tryParse(json['item_quantity'].toString()),
        cart_size: json['cart_size'],
        cart_color: json['cart_color'],
        item_name: json['item_name'],
        item_rating: double.tryParse(json['item_rating'].toString()),
        item_tags: json['item_tags'] != null 
            ? json['item_tags'].toString().split(', ') 
            : null,
        item_price: double.tryParse(json['item_price'].toString()),
        item_color: json['item_color'] != null 
            ? json['item_color'].toString().split(', ') 
            : null,
        item_size: json['item_size'] != null 
            ? json['item_size'].toString().split(', ') 
            : null,
        item_desc: json['item_desc'],
        item_image: json['item_image'],
      );
}

额外注意点

  • 确认接口返回的item_quantity字段与模型中的cart_quantity映射正确(你已核对数据库字段,此处保持原有映射)。
  • 在UI中使用可空字段时,添加null检查(比如cartModel.cart_color ?? '默认颜色'),避免直接用!强制解包引发新的空安全错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:37:46