首页 > 解决方案 > 我想在 ListView.builder 中显示 firestore 数组

问题描述

我在 Firestore 中有一个名为“Names”的数组。我想在 ListView.builder 中显示该数组元素。我尝试了很多方法,但无法做到。我不知道如何访问快照数据。

FutureBuilder(
                future: getList(),
                builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                    return CircularProgressIndicator();
                  } else {
                    return Center(
                      child: ListView.builder(
                          padding: const EdgeInsets.only(bottom: 20.0),
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                            return Center(
                              child: ListTile(
                                title: Text(
                                   snapshot.data[0].data), //snapshot data should dispaly in this text field
                              ),
                            );
                          }),
                    );
                  }
                },
              ),

这是我的 getList() 方法。

 Future<List<dynamic>> getList() async {
var firestore = Firestore.instance;

DocumentReference docRef =
    firestore.collection('RecodeBook').document('2019-05-04');
List<dynamic> info = new List<String>();
docRef.get().then((datasnapshot) {
  if (datasnapshot.exists) {
    info = datasnapshot.data['Names'].toList();
    print('#');
    print(info); //this line prints [aa, aghshs, fffg, fug, ghh, fggg, ghhh]
    print(info.length); //this line prints 7
  }
});
return info;

}

标签: dartflutter

解决方案


似乎是因为您要发回 aList<dynamic>而不是 a Future<List<dynamic>>。以下代码应该可以工作

Future<List<dynamic>> getList() async {
  var firestore = Firestore.instance;

  DocumentReference docRef = firestore.collection('RecodeBook').document('2019-05-04');

  return docRef.get().then((datasnapshot) {
    if (datasnapshot.exists) {
      List<dynamic> info = datasnapshot.data['Names'].toList();
      print('#');
      print(info); //this line prints [aa, aghshs, fffg, fug, ghh, fggg, ghhh]
      print(info.length); //this line prints 7
      return info;
    }
  });
}

另外,请ListView.builder注意索引。

title: Text(
  snapshot.data[index].data), //snapshot data should display in this text field

推荐阅读