Why is there an error with snapshot.data.length?

Issue

I am trying to parse data from an API. For that, I am using FutureBuilder to list all the parsed data in a ListView.

I’ve performed a check for nullity of snapshot.data but I keep on getting this error in the segment snapshot.data.length, it says, 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 ('!').

I’ve a similar error in the snapshot.data[i] section, which says 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 ('!').

Here is my code’s section of the same:

 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,
                    );
                  });
            }
          },
        ),
      ),

Here’s 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;
}

Solution

if u are using a new version of flutter (2.2.0 or above). first try adding a null check to the target (‘!’). because of the null safety feature.

 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,
                );
              });
        }
      },
    ),
  ),

then try specifying the FutureBuilder type to a List of Data type

 body: Container(
    child: FutureBuilder<List<Data>>(
      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,
                );
              });
        }
      },
    ),
  ),

Answered By – Adel Cherfaoui

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *