【发布时间】: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 为空时尝试访问数据。
【问题讨论】: