【问题标题】:NoSuchMethodError: The method '[]' was called on null - FlutterNoSuchMethodError:在 null 上调用了方法 '[]' - Flutter
【发布时间】:2021-09-29 18:26:24
【问题描述】:

我想以这种方式从this JSON 中读取数据(请阅读代码注释):

class Profile extends StatefulWidget {
  final id;

  Profile({Key? key, @required this.id}) : super(key: key);

  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  var data;
  @override
  void initState() {
    super.initState();
    void getData() async {
      Response response = await get(
          Uri.parse('https://en.gravatar.com/' + widget.id + '.json'));
      this.data = json.decode(utf8.decode(response.bodyBytes));
      // READ PLEASE >>> Data successfully is loaded from server & if you 
      // print this.data it will show full data in console <<< READ PLEASE
    }

    getData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Profile | MWX Gravatar Viewer',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Profile | MGV'),
        ),
        body: Center(
          child: Column(
            children: [
              Text(this.data['entry'][0]['name']['familyName']), // Where raises error
            ],
          ),
        ),
      ),
    );
  }
}

渲染页面时出现此错误:

The following NoSuchMethodError was thrown building Profile(dirty, state: _ProfileState#35267):
The method '[]' was called on null.
Receiver: null
Tried calling: []("entry")

注意:热重载错误消失后,我可以在屏幕上看到我需要的数据,但每次我想加载页面时,都会显示此错误,尽管我可以看到我的内容预期,在热重载之后

【问题讨论】:

    标签: json flutter dictionary dart mobile


    【解决方案1】:

    您的身体可能正在运行,而不是在 initState 上等待您的 getData()。在使用之前尝试检查它是否为空:

    body: Center(
              child: Column(
                children: [
                  Text(this.data != null ? this.data['entry'][0]['name']['familyName'] : 'no data'), // Where raises error
                ],
              ),
            ),
    

    或者使用FutureBuilder

    【讨论】:

      【解决方案2】:

      这是因为您正在调用网络请求,同时您正在使用默认为 null 的数据,因此您可以使用 FutureBuilder() 或通过 null check 处理错误

      【讨论】:

        猜你喜欢
        • 2020-06-07
        • 2019-03-10
        • 2020-04-09
        • 2020-05-23
        • 1970-01-01
        • 2021-11-30
        • 2020-06-07
        • 2020-08-11
        • 2020-05-05
        相关资源
        最近更新 更多