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

如何在Flutter现有模型中新增变量并解决初始化后空值问题

问题原因

  • 你通过API反序列化生成DishMenuTypesIdData实例时,调用的是fromJson命名构造函数,而非设置了qty默认值的默认无参构造函数,默认构造的初始值不会在fromJson构造中生效。
  • 你当前的fromJson逻辑里,仅尝试从JSON中读取qty字段赋值,而接口返回的JSON数据中根本不存在qty字段,因此qty最终会被赋值为null。
  • 额外问题:你要求qty是int类型,但现有代码中将其定义为String?类型,默认值也设为了字符串"1",和需求的类型不符。

解决方法

修改DishMenuTypesIdData类的代码即可,有两种常用实现方式:

方式1:在fromJson中直接增加兜底默认值

class DishMenuTypesIdData {
  // 改为需求的int类型
  int? qty;
  String? id;

  DishMenuTypesIdData({
    this.qty = 1,
    this.id,
  });

  DishMenuTypesIdData.fromJson(Map<String, dynamic> json) {
    // json中不存在qty时兜底赋值为1
    qty = json["qty"] as int? ?? 1;
    id = json["id"]?.toString();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data["qty"] = qty;
    data["id"] = id;
    return data;
  }
}

方式2:fromJson构造重定向到默认构造,复用默认值逻辑

class DishMenuTypesIdData {
  int qty;
  String? id;

  // qty可以定义为非空类型减少后续判空逻辑
  DishMenuTypesIdData({
    this.qty = 1,
    this.id,
  });

  DishMenuTypesIdData.fromJson(Map<String, dynamic> json) : this(
    qty: json["qty"] as int? ?? 1,
    id: json["id"]?.toString(),
  );

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data["qty"] = qty;
    data["id"] = id;
    return data;
  }
}

两种方式都可以保证反序列化出来的实例qty字段不会为null,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:15:03