![](/img/trans.png)
[英]Flutter and Firestore: How can I get the document Id from the add function?
[英]Firestore / Flutter - How can I get document Id?
這是我的代碼
Future _save() async {
final StorageReference storageRef = FirebaseStorage.instance.ref().child('product/'+nameController.text+'.jpg');
final StorageUploadTask task = storageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await task.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
StorageMetadata created = await taskSnapshot.ref.getMetadata();
Firestore.instance.collection('product').document()
.setData({
'name': nameController.text,
'price': int.tryParse(priceController.text),
'description': descriptionController.text,
'creator': widget.user.uid,
'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
'url': downloadUrl,
'id': //I want to set document Id here //
});
}
我怎樣才能得到這個隨機生成的文檔的 ID? 感謝您的幫助
collection
您可以添加document
並接收DocumentReference
。
final docRef = await Firestore.instance.collection('product').add({
'name': nameController.text,
'price': int.tryParse(priceController.text),
'description': descriptionController.text,
'creator': widget.user.uid,
'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
'url': downloadUrl,
});
現在您可以獲取文檔 ID:
docRef.documentID
你這樣做
DocumentReference documentReference = Firestore.instance.collection('product').document();
documentReference.setData({
'name': nameController.text,
'price': int.tryParse(priceController.text),
'description': descriptionController.text,
'creator': widget.user.uid,
'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
'url': downloadUrl,
'id': documentReference.documentID
});
文件編號
documentReference.documentID
已棄用:documentID 已被棄用,取而代之的是 id。
所以而不是
ref.documentId
用
ref.id
檢索隨機生成的文檔 ID。
您可以通過調用您的 ref.documentID 來獲取 ID
使用value.Id獲取 partgiculer documentId 。
CollectionReference users = FirebaseFirestore.instance.collection('candidates');
Future<void> registerUser() {
// Call the user's CollectionReference to add a new user
return users.add({
'name': enteredTextName, // John Doe
'email': enteredTextEmail, // Stokes and Sons
'profile': dropdownValue ,//
'date': selectedDate.toLocal().toString() ,//// 42
})
.then((value) =>(showDialogNew(value.id)))
.catchError((error) => print("Failed to add user: $error"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.