skip to Main Content

My SETUP:
Visual Studio Code
Version: 1.52.0
Node.js: 12.14.1

Here below is the code snippet in Flutter.
The problem is being in the .length code snippet
I think it shouldn’t show any errors, because through the if, it already guarantees that the asynchronous request was completed and that snapshop has some data.

I think it’s more the editor’s problem than the Fluter language.

body: FutureBuilder<List<Post>>(
        future: postServiceData,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done && snapshot.hasData){ //See it
            return ListView.builder(
                itemCount: snapshot.data.length, // Error on this line because .length
                itemBuilder: (context, index) {
                  final post = snapshot.data![index];
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ListTile(
                      title: Text(post.title.toUpperCase()),
                      subtitle: Text(post.body),
                      onTap: () {
                        // Faça algo quando o item da lista for clicado
                      },
                    ),
                  );
                });
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),

To work around this problem, I’m having to replace the error snippet with this one:

itemCount: snapshot.data!.length,

I already mentioned above.

2

Answers


  1. Chosen as BEST ANSWER

    Future me figured out what causes this problem, it's actually not having a definition of what a snapshot is. Well they could make the snapshot not need to be defined..

    So in this case the right way to do it is:

    body: FutureBuilder<List<Post>>(
        future: postServiceData,
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  final post = snapshot.data[index];
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ListTile(
                      title: Text(post.title.toUpperCase()),
                      subtitle: Text(post.body),
                      onTap: () {
                        // Faça algo quando o item da lista for clicado
                      },
                    ),
                  );
                });
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    

  2. replace the builder by doing:

    builder: (context, AsyncSnapshot<List<Post>> snapshot)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search