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

Flutter解决CallListDto为空时map调用空值错误问题

解决“map was called on a null value”错误

问题根源是当API返回的callListDto字段为null时,你的Login.fromJson方法直接对null值调用了map方法,导致空指针异常。以下是具体修复方案:

核心修复逻辑

在解析callListDto字段时,先判断其是否为null,将null转换为空列表后再执行map操作,同时优化模型构造逻辑增强空值安全性。

修改后的完整代码

Login loginFromJson(String str) => Login.fromJson(json.decode(str));

String loginToJson(Login data) => json.encode(data.toJson());

class Login {
  Login({
    required this.token,
    // 为callListDto设置默认空列表,避免实例化时必须传入
    this.callListDto = const [],
  });

  String token;
  List<CallListDto> callListDto;

  factory Login.fromJson(Map<String, dynamic> json) => Login(
        token: json["token"],
        // 若字段为null则用空列表替代,确保后续map操作安全
        callListDto: List<CallListDto>.from(
          (json["callListDto"] ?? []).map((x) => CallListDto.fromJson(x)),
        ),
      );

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

class CallListDto {
  CallListDto({
    required this.callId,
    required this.stationCode,
    required this.callType,
  });

  int callId;
  String stationCode;
  int callType;

  factory CallListDto.fromJson(Map<String, dynamic> json) => CallListDto(
        callId: json["callID"],
        stationCode: json["stationCode"],
        callType: json["callType"],
      );

  Map<String, dynamic> toJson() => {
        "callID": callId,
        "stationCode": stationCode,
        "callType": callType,
      };
}

补充说明

  • json["callListDto"] ?? []的作用是:无论API返回null还是空数组,都能得到一个可安全调用map的列表,彻底避免空指针。
  • 给Login构造函数的callListDto设置默认空列表,避免手动创建Login实例时因未传入该字段报错。
  • 修复后,即使callListDto为空列表,填充下拉菜单时也不会触发错误,空列表只会生成空的下拉选项集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:10:54