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

Flutter中Null check operator空指针异常排查求助

解决Flutter中Parish列表映射时的空指针异常

问题描述

在Flutter项目中尝试获取Parish列表并映射到自定义模型类,以便逐个引用数据时,触发了Null check operator used on a null value空指针异常。堆栈信息显示异常出现在ParishResponse.fromJson方法的第42行。通过打印日志确认服务器返回的Parish数据完整有效,但调用data!.add(ParishData.fromJson(e))时出错。

相关代码

class ParishResponse {
  int? code;
  String? title;
  String? message;
  List<ParishData>? data;

  ParishResponse(this.code, this.title, this.message, this.data);

  ParishResponse.fromJson(Map<String, dynamic> json) {
    code = json["code"];
    title = json["title"];
    message = json["message"];
    if (json['data'] != null) {
      json['data'].forEach((e) {
        print("This are the parishes ${e.toString()}");
        print("The parish name in the list are ${ParishData.fromJson(e).name}");
        
        // 此处触发空指针异常
        data!.add(ParishData.fromJson(e));
      });
    }
  }
}

class ParishData {
  int? id;
  String? name;
  String? acronym;
  String? address;
  String? phoneNo;
  String? parishPriestName;
  Town? town;
  State? state;
  Country? country;
  Diocese? diocese;
  Attachments? attachments;

  ParishData(
      {this.id,
      this.name,
      this.acronym,
      this.address,
      this.phoneNo,
      this.parishPriestName,
      this.town,
      this.state,
      this.country,
      this.diocese,
      this.attachments});

  ParishData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    acronym = json['acronym'];
    address = json['address'];
    phoneNo = json['phone_no'];
    parishPriestName = json['parish_priest_name'];
    if (json['town'] != null) {
      town = Town.fromJson(json['town']);
    }
    if (json['state'] != null) {
      state = State.fromJson(json['state']);
    }
    if (json['country'] != null) {
      country = Country.fromJson(json['country']);
    }
    if (json['diocese'] != null) {
      diocese = Diocese.fromJson(json['diocese']);
    }
    if (json['attachments'] != null) {
      attachments = Attachments.fromJson(json['attachments']);
    }
  }
}

问题原因

核心问题是ParishResponse类中的data成员变量初始值为null,在fromJson方法中处理服务器返回的json['data']时,没有提前初始化data列表就直接调用data!.add()。空检查运算符!强制断言data不为空,但此时data尚未被实例化,因此触发空指针异常。

解决方法

方法一:提前初始化data列表

在遍历json['data']之前,先将data初始化为空列表,避免空指针:

ParishResponse.fromJson(Map<String, dynamic> json) {
  code = json["code"];
  title = json["title"];
  message = json["message"];
  if (json['data'] != null) {
    // 初始化data为空列表
    data = [];
    json['data'].forEach((e) {
      print("This are the parishes ${e.toString()}");
      print("The parish name in the list are ${ParishData.fromJson(e).name}");
      data!.add(ParishData.fromJson(e));
    });
  } else {
    // 可选:若服务器返回data为null,也初始化空列表避免后续使用出错
    data = [];
  }
}

方法二:使用集合映射的简洁写法(推荐)

利用List.from配合map直接转换列表,无需手动遍历,同时自动处理空值情况:

ParishResponse.fromJson(Map<String, dynamic> json) {
  code = json["code"];
  title = json["title"];
  message = json["message"];
  // 直接转换json数组为ParishData列表,若json['data']为null则返回空列表
  data = json['data'] != null 
      ? List.from(json['data'].map((e) => ParishData.fromJson(e)))
      : [];
}

额外优化建议

  • 可为ParishResponse的构造函数添加命名参数,提升代码可读性;
  • 确保嵌套模型(如Town、State等)的fromJson方法也正确处理空值,避免后续嵌套解析出现异常;
  • 若业务允许data为空列表而非null,可在声明时直接初始化data为List<ParishData>? data = [];,减少空值判断代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:02:21