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

查看:139
本文介绍了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):接收方:空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.

例如,让我们假设您看到了:

For example, let's imagine you see:

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.

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天全站免登陆