-- 之前,我尝试以另一种形式解析 json 并且它有效,当我尝试像这样为上面的 json 构建结构时:
class HomeTeam {
final int id, legacyId, name, countryId;
final bool nationalTeam;
final String logoPath;
HomeTeam({this.id, this.legacyId, this.name, this.countryId, this.nationalTeam, this.logoPath});
factory HomeTeam.fromJson(Map<String, dynamic> json){
return HomeTeam(
id: json['id'],
legacyId: json['legacy_id'],
name: json['name'],
nationalTeam: json['national_team'],
logoPath: json['logo_path']
);
}
}
.
homeTeam: HomeTeam.fromJson(json['localTeam']['data']),
然后结果出现错误..
NoSuchMethodError: The method '[]' was called on null. E/flutter ( 220): Receiver: null E/flutter: Tried calling:
如何解决这个问题?
最佳答案
错误消息 NoSuchMethodError: The method '[]' was called on null.
告诉您您已经在 null 上调用了索引 ([]
) 运算符.
如果您的问题中没有精简的代码示例和 JSON 数据,或者没有指向代码中特定行的堆栈跟踪,则很难判断哪个值为 null。您需要检查堆栈跟踪并查看发生故障的行号。
例如,假设您看到:
Unhandled exception:
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("data")
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 main (file:///Users/cbracken/foo.dart:3:23)
...
上面的堆栈跟踪告诉您,对空对象的调用是在文件 foo.dart 的第 3 行的 main
中。此外,它告诉您 []
运算符是使用参数 'data'
调用的。如果我查看代码中的那一行,它显示 var foo = json['localteam']['data']
,那么我会推断出 json['localteam']
返回 null。
关于android - flutter - 在 null 上调用了方法 '[]'(解析 json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53009529/