在Dart的Cloud Firestore中添加文档后如何获取文档ID [英] How do you get the document id after adding document in Cloud Firestore in Dart
问题描述
我使用以下代码通过Dart / Flutter更新了Cloud Firestore集合。
Im using the following code to update a Cloud Firestore collection using Dart/Flutter.
final docRef = Firestore.instance.collection('gameLevels');
docRef.document().setData(map).then((doc) {
print('hop');
}).catchError((error) {
print(error);
});
我正在尝试获取将文档添加到集合中时创建的documentID,但( )参数返回为null。我以为应该是documentReference?
I'm trying to get the documentID created when I add the document to the collection but the (doc) parameter comes back as null. I thought it was supposed to be a documentReference?
由于它为null,因此我显然不能使用doc.documentID。
Since it's null, I obviously can't use doc.documentID.
我在做什么错了?
推荐答案
您可以尝试以下操作:
DocumentReference docRef = await
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);
由于add()方法创建新文档并自动生成ID,因此您不必显式调用文档()方法
Since add() method creates new document and autogenerates id, you don't have to explicitly call document() method
或者如果您想使用然后回调,请尝试以下操作:
Or if you want to use "then" callback try the following:
final collRef = Firestore.instance.collection('gameLevels');
DocumentReferance docReference = collRef.document();
docReferance.setData(map).then((doc) {
print('hop ${docReferance.documentID}');
}).catchError((error) {
print(error);
});
这篇关于在Dart的Cloud Firestore中添加文档后如何获取文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!