阅读 94

flutter 1.升级2.X在模型类中序列化JSON报错Non-nullable instance field 'title' must be initialized.

flutter 1.升级2.X在模型类中序列化JSON报错

Non-nullable instance field ‘title‘ must be initialized. 
Try adding an initializer expression, 
or add a field initializer in this constructor, or mark it ‘late‘.

修改方案--添加late


原有代码

class Autogenerated {
  List result;

  Autogenerated({this.result});

  Autogenerated.fromJson(Map json) {
    if (json[‘result‘] != null) {
      result = new List();
      json[‘result‘].forEach((v) {
        result.add(new Result.fromJson(v));
      });
    }
  }

  Map toJson() {
    final Map data = new Map();
    if (this.result != null) {
      data[‘result‘] = this.result.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Result {
  String sId;
  String title;
  String status;
  String pic;
  String url;

  Result({this.sId, this.title, this.status, this.pic, this.url});

  Result.fromJson(Map json) {
    sId = json[‘_id‘];
    title = json[‘title‘];
    status = json[‘status‘];
    pic = json[‘pic‘];
    url = json[‘url‘];
  }

  Map toJson() {
    final Map data = new Map();
    data[‘_id‘] = this.sId;
    data[‘title‘] = this.title;
    data[‘status‘] = this.status;
    data[‘pic‘] = this.pic;
    data[‘url‘] = this.url;
    return data;
  }
}

修改后的

class Autogenerated {
  late List result;

  Autogenerated({required this.result});

  Autogenerated.fromJson(Map json) {
    if (json[‘result‘] != null) {
      result = [];
      json[‘result‘].forEach((v) {
        result.add(new Result.fromJson(v));
      });
    }
  }

  Map toJson() {
    final Map data = new Map();
    if (this.result != null) {
      data[‘result‘] = this.result.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Result {
  late String sId;
  late String title;
  late String status;
  late String pic;
  late String url;

  Result(
      {required this.sId,
      required this.title,
      required this.status,
      required this.pic,
      required this.url});

  Result.fromJson(Map json) {
    sId = json[‘_id‘];
    title = json[‘title‘];
    status = json[‘status‘];
    pic = json[‘pic‘];
    url = json[‘url‘];
  }

  Map toJson() {
    final Map data = new Map();
    data[‘_id‘] = this.sId;
    data[‘title‘] = this.title;
    data[‘status‘] = this.status;
    data[‘pic‘] = this.pic;
    data[‘url‘] = this.url;
    return data;
  }
}

原文:https://www.cnblogs.com/sugartang/p/15302924.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐