如何在flutter的列表视图中显示Firebase数组

时间:2020-06-02 05:04:16

标签: firebase flutter dart google-cloud-firestore

enter image description here

Future<List<DocumentSnapshot>> getData() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
        .collection("UserTransactions")
        .where("AuthUserId", isEqualTo: userId)
        .getDocuments();
    return qn.documents;
}

在这里,我根据ID获取所有文档,我想在列表视图中显示作为数组的交易

FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
        return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (_, index) {
                return Text(snapshot.data[index].data["transactions"][index]["Mode"])
            })
    }
); 

我遇到了错误:

The getter 'length' was called on null.
Receiver: null
Tried calling: length

如何显示这些值,如果数组为空,则什么也不显示?

1 个答案:

答案 0 :(得分:1)

您需要检查是否未全部检索到数据

 FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
             if(snapshot.hasData){
             return ListView.builder(
                       itemCount: snapshot.data.length,
                       itemBuilder: (_, index) {
                       return Text(snapshot.data[index].data["transactions"][index]["Mode"])  
                       }
           return CircularProgressIndicator();
        }
  )

使用snapshot.hasData检查是否检索到数据,并使用CircularProgressIndicator显示加载图标,直到完全检索数据为止。