简体   繁体   中英

How to get id of a specific document from cloud_firestore flutter

在此处输入图像描述 I can't seem to find a way to get the id of a specific document in a collection from cloud_firestore

I solved it with adding the document id to the specific document itself. When you creating new collections and documents you can reach the document id and add it to your document like this:

DocumentReference docRef = await _fireStore.collection('${username}_user_data').add({
                    'friends': [],
                    'sent_friend_requests' : [],
                    'private_conversations' : [],
                  });
                  String docId = docRef.id;
                  await FirebaseFirestore.instance.collection('${username}_user_data').doc(docId).update(
                      {
                        'id' : docId
                      });

In my example, i created a document reference object when creating the collection/document. Then reaching that docrefs id and adding the id to the very document itself as a field.

When you have to reach/find that specific document id i have this code example related to code example above :

 Future<String> getDocumentRef (String userDisplayName) async{

var collection = FirebaseFirestore.instance.collection('${userDisplayName}_user_data');
var querySnapshot = await collection.get();

var docRef;

for (var queryDocumentSnapshot in querySnapshot.docs) {
  Map<String, dynamic> data = queryDocumentSnapshot.data();
  docRef = data['id'];
}

return docRef;
}

I don't know if this is helps or not but i solved the exact problem like this. If anyone has better solution, i'll be happy to learn more!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM