【问题标题】:The method '[]' was called on null exception flutter空异常颤动时调用了方法“[]”
【发布时间】:2021-07-25 12:05:29
【问题描述】:

我正在使用 API 调用来获取一些数据。我在初始化状态下调用该方法,以便在将小部件添加到树中后立即获取数据。

我在文本小部件中使用该数据,但它显示错误 “方法 '[]' 在 null 上被调用”

以下是供您参考的代码:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Profile extends StatefulWidget {
  final String username;
  Profile({this.username});
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  var data;

  void getData() async {
    http.Response response = await http
        .get('http://codeforces.com/api/user.info?handles=${widget.username}');

    if (response.statusCode == 200) {
      data = jsonDecode(response.body);
    } else {
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Column(
          children: [
            Text('Handle - ${widget.username}'),
            Text(data['result'][0]['firstName']),            /*This line causes error*/
          ],
        ),
      ),
    );
  }
}

问题是为什么data字段在init状态下被调用,并且API调用也成功,却为null?

我已经使用注释标记了给出错误的行。

【问题讨论】:

  • 结果数组不包含错误信息所指示的任何值

标签: api flutter dart flutter-layout


【解决方案1】:

不是最好和最有效的解决方案,但如果您只想显示一些数据,例如用户名或电子邮件,您可以这样做:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(Profile());

class Profile extends StatefulWidget {
  final String username;
  Profile({this.username});
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  var email;
  void getData() async {
    http.Response response = await http.get(Uri.parse(
        'http://codeforces.com/api/user.info?handles=${widget.username}'));
    if (response.statusCode == 200) {
      setState(() {
        Map<String, dynamic> map = json.decode(response.body);
        email = map['result'][0]['email'];
        print(email);
      });
    } else {
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: email == null
              ? CircularProgressIndicator()
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text('Handle - ${widget.username}'),
                    Text(email),
                  ],
                ),
        ),
      ),
    );
  }
}

输出:

【讨论】:

    【解决方案2】:

    我认为这可能会发生,因为在完成请求时,您的 Profile 小部件已经呈现,并且您没有在 getData() 函数中使用 setState,因此,小部件将不再渲染。

    在这种情况下,您可以对代码进行一些更改:

    在 getData 方法中使用 setState

    void getData() async {
      http.Response response = await http
        .get('http://codeforces.com/api/user.info?handles=${widget.username}');
      if (response.statusCode == 200) {
        setState(() {
          data = jsonDecode(response.body);
        });
      } else {
        print('Something went wrong.');
      }
    }
    

    为您的文本小部件设置默认值

    Text(data != null ? data['result'][0]['firstName'] : ''),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2013-09-17
      • 2021-06-10
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多