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

Quicktype生成的Dart模型空安全错误修复咨询

Dart空安全下JSON模型的错误修复方案

以下是你提供的Dart JSON模型代码:

import 'dart:convert';

Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));

String hisselistToJson(Hisselist data) => json.encode(data.toJson());

class Hisselist {
  Hisselist({
    required this.code,
    required this.data,
  });

  String code;
  List<Datum> data;

  factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
        code: json["code"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "code": code,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    required this.id,
    required this.kod,
    required this.ad,
    required this.tip,
  });

  int id;
  String kod;
  String ad;
  Tip tip;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        kod: json["kod"],
        ad: json["ad"],
        tip: tipValues.map[json["tip"]],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "kod": kod,
        "ad": ad,
        "tip": tipValues.reverse[tip],
      };
}

enum Tip { HISSE }

final tipValues = EnumValues({"Hisse": Tip.HISSE});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

你遇到的两个空安全相关错误可以按以下方式修复:

错误1:Non-nullable instance field 'reverseMap' must be initialized.

问题原因:空安全规则下,非空类型的实例字段必须在构造时初始化,而reverseMap是在reverse getter中才被赋值的,属于延迟初始化场景。

修复方案:给reverseMap字段添加late关键字,标记它为延迟初始化:

class EnumValues<T> {
  Map<String, T> map;
  late Map<T, String> reverseMap; // 添加late关键字

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

错误2:The argument type 'Tip?' can't be assigned to the parameter type 'Tip'.

问题原因:tipValues.map[json["tip"]]返回的是Tip?类型(因为Map的[]操作符可能返回null,比如JSON中没有tip字段或值不匹配),但Datum的tip字段是非空的Tip类型,类型不兼容。

修复方案(可选其一):

  1. 断言非空:如果你能确保JSON中的tip字段一定存在且值有效,直接用!断言:
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
      id: json["id"],
      kod: json["kod"],
      ad: json["ad"],
      tip: tipValues.map[json["tip"]]!, // 添加!断言
    );
  1. 提供默认值:如果JSON中tip可能缺失,指定一个默认值:
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
      id: json["id"],
      kod: json["kod"],
      ad: json["ad"],
      tip: tipValues.map[json["tip"]] ?? Tip.HISSE, // 用??提供默认值
    );
  1. 抛出错误:如果tip字段缺失或无效属于异常情况,直接抛出错误:
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
      id: json["id"],
      kod: json["kod"],
      ad: json["ad"],
      tip: tipValues.map[json["tip"]] ?? (throw ArgumentError("无效的tip值: ${json["tip"]}")),
    );

修复后的完整代码

import 'dart:convert';

Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str));

String hisselistToJson(Hisselist data) => json.encode(data.toJson());

class Hisselist {
  Hisselist({
    required this.code,
    required this.data,
  });

  String code;
  List<Datum> data;

  factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
        code: json["code"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "code": code,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    required this.id,
    required this.kod,
    required this.ad,
    required this.tip,
  });

  int id;
  String kod;
  String ad;
  Tip tip;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        kod: json["kod"],
        ad: json["ad"],
        tip: tipValues.map[json["tip"]]!, // 使用断言修复类型问题
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "kod": kod,
        "ad": ad,
        "tip": tipValues.reverse[tip],
      };
}

enum Tip { HISSE }

final tipValues = EnumValues({"Hisse": Tip.HISSE});

class EnumValues<T> {
  Map<String, T> map;
  late Map<T, String> reverseMap; // 添加late修复初始化问题

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

内容的提问来源于stack exchange,提问作者Mıktad Tahir Durak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:54:25