【问题标题】:Fetching data from internet error when object is null对象为空时从 Internet 错误中获取数据
【发布时间】:2021-12-14 01:59:51
【问题描述】:

我有这个模型按预期工作,除非 InfoA 返回 null:

class ModelGTA {
  ModelGTA({
    required this.infoA,
    required this.infoB,
  });

  InfoA? infoA;
  InfoB? infoB;

  ModelGTA.fromJson(Map<String, dynamic> json) {
    infoA = InfoA.fromJson(json['infoA']);
    infoB = InfoB.fromJson(json['infoB']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['infoA'] = infoA!.toJson();
    _data['infoB'] = infoB!.toJson();
    return _data;
  }
}

class InfoA {
  InfoA({
    required this.data,
    required this.property,
  });

  Data? data;
  Property? property;


  InfoA.fromJson(Map<String, dynamic> json) {
    data = Data.fromJson(json['data']);
    property = Property.fromJson(json['property']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['data'] = data!.toJson();
    _data['property'] = property!.toJson();
    return _data;
  }
}

class Data {
  Dados({
    required this.number,
    required this.type,
  });

  String? number;
  String? type;

  Dados.fromJson(Map<String, dynamic> json) {
    numero = json['number'] ?? "";
    tipo = json['type'] ?? "";
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['number'] = number;
    _data['type'] = type;
    return _data;
  }
}

问题是当 infoA 返回 null 时,代码停止工作。我得到这个错误:

E/flutter ( 9958): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 9958): Receiver: null
E/flutter ( 9958): Tried calling: []("data")

我想知道是否有任何方法可以返回一个对象、带有空字符串的数据或防止程序在 InfoA 为空时尝试访问数据。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    为此更改您的方法 ModelGTA.fromJson

     ModelGTA.fromJson(Map<String, dynamic> json) {
        infoA =
    (json['infoA']==null)?[]: InfoA.fromJson(json['infoA']);
        infoB = InfoB.fromJson(json['infoB']);
      }
    

    【讨论】:

    • 当我尝试 json['infoA']==null)?[] 不会编译并显示此消息:'List' 无法分配给参数类型 'Map' 。当我尝试 json['infoA']==null)?{} 时,它会引发问题 E/flutter (9958) 中描述的相同错误:[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled异常:NoSuchMethodError:在 null 上调用了方法“[]”。
    猜你喜欢
    • 2017-02-21
    • 2018-03-23
    • 2022-01-23
    • 2020-11-22
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多