如何从Querysnapshot读取数据

时间:2020-01-01 12:35:40

标签: firebase flutter google-cloud-firestore

我想从Querysnapshot中读取数据。我使用futurebuilder但出现错误:

方法[]在null上被调用

小工具

FutureBuilder(
  future: getData('ac1'),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black)
      ),
      child: ListTile(
        title: Text(snapshot.data['name'].toString()),
        trailing: Text(snapshot.data['icon'].toString()),
        onTap: (){
          Navigator.push(context, MaterialPageRoute(builder: (context) => Ac()));
        },
      ),
    );
  },
),

功能

getData(String docId)async{
  final  QuerySnapshot snapshot = await Firestore
    .instance.collection('listofprods')
    .where('id', isEqualTo: docId)
    .getDocuments();

  return snapshot;
}

2 个答案:

答案 0 :(得分:1)

getData(String docId) async {
  final QuerySnapshot snapshot = await Firestore.instance.collection(
      'listofprods').where('id', isEqualTo: docId).getDocuments();
  return snapshot;
}
return FutureBuilder(
  future: getData('ac1'),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasData) {
      return Container(
        decoration:
        BoxDecoration(border: Border.all(color: Colors.black)),
        child: ListTile(
          title: Text(snapshot.data.documents[0].toString()),
          trailing: Text(snapshot.data.documents[0]['name'].toString()),
          onTap: () {
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Ac()));
          },
        ),
      );
    } else {
      return `Your widget
    `
  }

  },
);

您需要从文档中获取数据

答案 1 :(得分:0)

快照并不总是包含数据,因此您需要检查快照包含数据的情况,例如,这样修改可能会起作用

             FutureBuilder(
                future: getData('ac1'),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                 if(!snapshot.hasData || snapshot.hasError) return CircularProgressIndicator(); //line added
                 if(snapshot.hasData) //line added
                  return Container(
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.black)),
                    child: ListTile(
                      title: Text(snapshot.data['name'].toString()),
                      trailing: Text(snapshot.data['icon'].toString()),
                      onTap: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => Ac()));
                      },
                    ),
                  );
                },
         ),




 getData(String docId)async{
  //if this docId is the document id you cannot use where('id', isEqualTo: docId) to get document of that id instead use following
  final  DocumentSnapshot snapshot = await Firestore.instance.collection('listofprods').document(docId).get();
  return snapshot;
  }