英文:
Obtain Document ID immediately after you create a new document with Set in Firebase Flutter
问题
我需要获取我刚创建的文档的文档ID。
我使用以下代码创建新文档:
db.collection('Pack').doc().set({
'userId': userID,
'packName': newPackNameController.text.trim(),
'description': newPackDescriptionController.text.trim(),
//todo: 需要计算新重量或从此包中获取...
'totalWeight': '0.0',
'weightFormat': weightFormat,
});
接下来,我需要文档ID。
根据另一个Stack Overflow的问题,我尝试了以下方法:
DocumentReference docRef = await Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);
但这是用于添加集合而不是文档,我无法使用相同的代码来获取文档的ID。
英文:
In my app I need to get the document ID for a document I just created.
I am creating the new document with:
db.collection('Pack').doc().set({
'userId': userID,
'packName': newPackNameController.text.trim(),
'description': newPackDescriptionController.text.trim(),
//todo: need to calculate new weight or grab from this pack...
'totalWeight': '0.0',
'weightFormat': weightFormat,
});
Next I need to document ID.
I tried this based on another stack overflow question:
DocumentReference docRef = await
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);
But that was for adding a collection and not a document and I could not get the same code to work with a document.
答案1
得分: 1
The call to doc()
is a pure client-side operation, so you can split it from the set()
:
var ref = db.collection('Pack').doc();
print(ref.id);
ref.set({
'userId': userID,
'packName': newPackNameController.text.trim(),
'description': newPackDescriptionController.text.trim(),
//todo: need to calculate new weight or grab from this pack...
'totalWeight': '0.0',
'weightFormat': weightFormat,
});
Also see the last code sample in the documentation on adding a document.
英文:
The call to doc()
is a pure client-side operation, so you can split it from the set()
:
var ref = db.collection('Pack').doc();
print(ref.id);
ref.set({
'userId': userID,
'packName': newPackNameController.text.trim(),
'description': newPackDescriptionController.text.trim(),
//todo: need to calculate new weight or grab from this pack...
'totalWeight': '0.0',
'weightFormat': weightFormat,
});
Also see the last code sample in the documentation on adding a document.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论