[英]Flutter and Firestore: How can I get the document Id from the add function?
I added a document to Firestore.我向 Firestore 添加了一个文档。 How can I get the document Id of my added document?
如何获取我添加的文档的文档 ID? I want to save it to a variable.
我想将它保存到一个变量中。
Btw.顺便提一句。 I'm using this for a web app if this Is important.
如果这很重要,我将其用于 web 应用程序。
FirebaseFirestore.instance.collection('room').add({
'name': _name,
'points': 0,
});
Do this做这个
User user = FirebaseAuth.instance.currentUser;
FirebaseFirestore.instance.collection('room').add({
'id': user.uid,
'name': _name,
'points': 0,
});
Calling CollectionReference.add
returns a Future<DocumentReference>
, so you can get the ID from that:调用
CollectionReference.add
返回一个Future<DocumentReference>
,因此您可以从中获取 ID:
var newDocRef = await FirebaseFirestore.instance.collection('room').add({
'name': _name,
'points': 0,
})
var newDocId = newDocRef.id
If you want to store the ID inside the document, it's better to first create the DocumentReference
by calling CollectionReference.doc()
without paramters:如果要将 ID 存储在文档中,最好先通过调用
CollectionReference.doc()
不带参数来创建DocumentReference
:
var newDocRef = FirebaseFirestore.instance.collection('room').doc();
var newDocId = newDocRef.id
newDocRef.set({
'id': newDocId,
'name': _name,
'points': 0,
})
Add .then
method at the end.最后添加
.then
方法。
Do what ever you need with docRef.使用 docRef 做任何你需要的事情。
FirebaseFirestore.instance.collection('room').add({
'name': _name,
'points': 0,
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
The add
method on CollectionReference
returns a Future<DocumentReference>
. CollectionReference
上的add
方法返回Future<DocumentReference>
。 [ Documentation ] [ 文档]
Future<DocumentReference> add(Map<String, dynamic> data) async {
final DocumentReference newDocument = doc();
await newDocument.set(data);
return newDocument;
}
So, try this:所以,试试这个:
FirebaseFirestore.instance.collection('room')
.add({
'name': _name,
'points': 0,
})
.then((docRef) => print(docRef.id));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.