firebase 如何在Flutter中从Firestore检索数据

h5qlskok  于 2023-03-03  发布在  Flutter
关注(0)|答案(2)|浏览(122)

我是这样收集的:

var res = FirebaseFirestore示例集合(“酒店”);
var response =等待资源.doc(res.id).集合(数据.电子邮件).doc(数据.酒店名称).集合(数据.酒店名称).doc().集合('酒店详细信息').add('酒店名称':数据.酒店名称,'酒店电子邮件':data.email;

这是我使用的检索代码:

最终资源= FirebaseFirestore.示例.集合(“酒店”);
最后答复=等待资源文件(res.id).收集(电子邮件).get();

我在www.example.com中得到空列表response.docs

yzxexxkh

yzxexxkh1#

以后需要使用reference来检索文档。

var res = FirebaseFirestore.instance.collection("hotels");
 var docRef = res.doc(); // generates a new document reference with a unique ID
 var docId = docRef.id; // gets the ID of the new document reference    
 var data = {
  'hotel_name': data.hotelName,
  'hotel_email': data.email,
};
var response = await docRef.collection(data.email).doc(data.hotelName).collection(data.hotelName).doc(docId).set(data);

此外,要从子集合中检索文档,应该将document ID传递给doc()方法。

final snapshot = await 
res.doc(docId).collection(data.email).get();
if (snapshot.docs.isNotEmpty) {
  snapshot.docs.forEach((doc) {
    print(doc.data());
  });
} else {
  print('No documents found');
}
kwvwclae

kwvwclae2#

根据您的代码并对其进行必要的更正,要添加和检索数据,您可以按照以下方式进行操作。

使用set添加新酒店:

final newHotel = <String, dynamic>{
'hotel_name': data.hotelName,
'hotel_email': data.email,
};

 FirebaseFirestore.instance
                  .collection('hotels')
                  .doc(docId)           
                  .collection(data.email)
                  .doc(data.hotelName)
                  .collection(data.hotelName)
                  .doc()
                  .set(newHotel)
                  .onError((e, _) => print("Error writing document: $e"));

使用StreamBuilder检索数据:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<QuerySnapshot>(
          stream: .collection('hotels')
                  .doc(docId)           
                  .collection(data.email)
                  .doc(data.hotelName)
                  .collection(data.hotelName)
                  .snapshots(), 
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            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['hotel_name']), // 👈 You can access here
                subTitle: Text(data['hotel_email']),
              );
            }).toList());
          },
        ),
      ),
    );
  }

相关问题