flutter 从QuerySnapshot转换为Future〈列表〈Map〈动态,动态>>>

qnzebej0  于 2023-01-18  发布在  Flutter
关注(0)|答案(3)|浏览(129)

如何返回QuerySnapshot作为未来〉〉?
代码片段:

Future <List<Map<dynamic, dynamic>>>() {
List<Map<dynamic,dynamic>> list;
.....

.....
QuerySnapshot collectionSnapshot = await collectionRef.getDocuments();

list = collectionSnapshot.documents;  <--- ERROR
return list;

}

我想我需要使用的Map,但无法绕过它的工作。

bzzcjhmw

bzzcjhmw1#

collectionSnapshot.documents返回列表而不是列表类型,您需要将文档快照列表转换为List<Map<dynamic, dynamic>>

Future <List<Map<dynamic, dynamic>>> getCollection() async{
List<DocumentSnapshot> templist;
List<Map<dynamic, dynamic>> list = new List();
CollectionReference collectionRef = Firestore.instance.collection("path");
QuerySnapshot collectionSnapshot = await collectionRef.getDocuments();

templist = collectionSnapshot.documents; // <--- ERROR

list = templist.map((DocumentSnapshot docSnapshot){
  return docSnapshot.data;
}).toList();

return list;
}
v9tzhpje

v9tzhpje2#

加纳帕特的回答对我来说是正确的,只是做了一些小改动。

Future <List<Map<dynamic, dynamic>>> getCollection() async{
List<DocumentSnapshot> templist;
List<Map<dynamic, dynamic>> list = new List();
CollectionReference collectionRef = Firestore.instance.collection("path");
QuerySnapshot collectionSnapshot = await collectionRef.get(); // <--- This method is now get().

templist = collectionSnapshot.documents; // <--- ERROR

list = templist.map((DocumentSnapshot docSnapshot){
  return docSnapshot.data() as Map<Dynamic,Dynamic>; // <--- Typecast this.
}).toList();

 

return list;
}
ggazkfy8

ggazkfy83#

使用null safety更新2023

FutureBuilder中正确使用QuerySnapshot的方法如下:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore
                .instance
                .collection('users') // 👈 Your collection name here
                .get(), 
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          return ListView(
              children: snapshot.data!.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
            return ListTile(
              title: Text(data['avatar']), // 👈 Your valid data here
            );
          }).toList());
        },
      )),
    );
  }

另请参阅:How to use StreamBuilder and FutureBuilder for single and multiple documents

相关问题