在Dart的Cloud Firestore中添加文档后如何获取文档ID
问题内容:
我使用以下代码通过Dart / Flutter更新了Cloud Firestore集合。
final docRef = Firestore.instance.collection('gameLevels');
docRef.document().setData(map).then((doc) {
print('hop');
}).catchError((error) {
print(error);
});
我正在尝试将文档添加到集合中时创建的documentID,但(doc)参数返回为null。我以为应该是documentReference?
由于为空,因此我显然不能使用doc.documentID。
我究竟做错了什么?
问题答案:
您可以尝试以下方法:
DocumentReference docRef = await
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);
由于add()方法创建新文档并自动生成ID,因此您无需显式调用document()方法
或者,如果您想使用“ then”回调,请尝试以下操作:
final collRef = Firestore.instance.collection('gameLevels');
DocumentReferance docReference = collRef.document();
docReferance.setData(map).then((doc) {
print('hop ${docReferance.documentID}');
}).catchError((error) {
print(error);
});