首页 > 解决方案 > 为什么 snapshot.data.length 有错误?

问题描述

我正在尝试从 API 解析数据。为此,我使用 FutureBuilder 在 ListView 中列出所有已解析的数据。

我已经检查了 of 的无效性,snapshot.data但我一直在段中收到此错误snapshot.data.length,它说,The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').

我在该snapshot.data[i]部分中有一个类似的错误,它说The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').

这是我的代码部分:

 body: Container(
        child: FutureBuilder(
          future: getData('hello'),
          builder: (context, snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("Loading"),
              );
            }else{
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: snapshot.data[i].partOfSpeech,
                    );
                  });
            }
          },
        ),
      ),

这是 getData(String s):

Future<List> getData(String s) async {
  var response = await http
      .get(Uri.https('api.dictionaryapi.dev', 'api/v2/entries/en_US/' + s));
  var jsonData = jsonDecode(response.body)[0];

  List<Data> data = [];

  for (var x in jsonData["meanings"]) {
    String definition = x["definitions"][0]["definition"];
    Data d = Data(x["partOfSpeech"], definition);
    data.add(d);
  }

  return data;
}

标签: flutterdartflutter-futurebuilder

解决方案


继续这个答案,我找到了解决问题的方法。显然 getData 没有按预期返回 List 。相反,它返回一个对象。

对象类型转换为列表解决了这个问题。

这是更正后的代码:

body: Container(
        child: FutureBuilder(
          future: getData('hello'),
          builder: (context, snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Text("Loading"),
              );
            }else{
              //typecasting Object to List
              var data = (snapshot.data as List<Data>).toList();
              return ListView.builder(
                  itemCount: data.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: data[i].partOfSpeech,
                    );
                  });
            }
          },
        ),
      ),

推荐阅读