flutter - 方法 '[]' 在 null 上调用(解析 json) [英] flutter - The method '[]' was called on null (parse json)

查看:48
本文介绍了flutter - 方法 '[]' 在 null 上调用(解析 json)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用这样的 Json 结构制作模型"?

how do make a 'Model' with a Json structure like this?

--之前,我尝试以另一种形式解析 json 并且它起作用了,当我尝试像这样为上面的 json 制作结构时:

-- beforely, I tried parsing json in another form and it worked, and when I tried to make the structure for json above like this:

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: 方法 '[]' 在 null 上被调用.E/颤振 (220): 接收者: null E/flutter: 尝试调用:

NoSuchMethodError: The method '[]' was called on null. E/flutter ( 220): Receiver: null E/flutter: Tried calling:

如何解决这个问题?

推荐答案

错误信息 NoSuchMethodError: The method '[]' was called on null. 告诉你你已经调用了索引([]) 运算符为 null.

The error message NoSuchMethodError: The method '[]' was called on null. is telling you that you've called the index ([]) operator on null.

如果您的问题中没有简化的代码示例和 JSON 数据,或者没有指向代码中特定行的堆栈跟踪,则很难判断哪个值为 null.您需要检查堆栈跟踪并查看发生故障的行号.

Without a reduced code sample and JSON data in your question, or a stack trace that points to a particular line in your code, it's hard to tell which value is null. You'll want to examine the stack trace and look at the line number where the failure occurred.

例如,假设您看到:

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']code> 返回 null.

The stack trace above is telling you that the call on the null object was in main on line 3 of file foo.dart. Further, it's telling you that the [] operator was called with the parameter 'data'. If I look at that line in my code and it says var foo = json['localteam']['data'], then I would deduce that json['localteam'] is returning null.

这篇关于flutter - 方法 '[]' 在 null 上调用(解析 json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆