首页 > 解决方案 > Flutter 上 Listview 的快照长度

问题描述

我需要在 Flutter 上实现一个 ListView,并且我将 snapshot.data.length 作为 itemCount 的参数传递:

return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(                            
snapshot.data[index].data["Identificacao"],...

然后我得到一个错误:

I/flutter ( 4647): Class 'List<DocumentSnapshot>' has no instance getter 'length'.
I/flutter ( 4647): Receiver: Instance(length:1) of '_GrowableList'
I/flutter ( 4647): Tried calling: length

但是我看过的许多教程中都使用了这些语法。我试过使用:

snapshot.data.documents.length;

但结果是一样的。请帮我!

标签: listviewfluttersnapshot

解决方案


如果您使用的是 StreamBuilder,那么查找数据长度的方法就不是这样了。

snapshot.data.length

由于您询问快照实例的长度,因此将无法正常工作,因此您将没有这样的方法没有这样的类错误

所以你应该做的是。

snapshot.data.snapshot.value.length

让我给你看一个例子

StreamBuilder(
    stream: FirebaseDatabase.instance
              .reference()
              .child("users")
              .orderByChild('firstName')
              .limitToFirst(20)
              .onValue,
    builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.snapshot.value.lenght,//Here you can see that I will get the count of my data
                  itemBuilder: (context, int) {
                  //perform the task you want to do here
                    return Text("Item count ${int}");
                  });
            } else {
              return Container();
            }
      },
  ),

你也可以看看这个关于stream和futurbuilder有什么区别的答案https://stackoverflow.com/a/50844913/9949983


推荐阅读