Jus*_*ain 4 dart flutter google-cloud-firestore
我使用以下代码通过Dart / Flutter更新了Cloud Firestore集合。
final docRef = Firestore.instance.collection('gameLevels');
docRef.document().setData(map).then((doc) {
print('hop');
}).catchError((error) {
print(error);
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试将文档添加到集合中时创建的documentID,但(doc)参数返回为null。我以为应该是documentReference?
由于为空,因此我显然不能使用doc.documentID。
我究竟做错了什么?
您可以尝试以下方法:
DocumentReferance docRef = await
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);
Run Code Online (Sandbox Code Playgroud)
由于add()方法创建新文档并自动生成ID,因此您无需显式调用document()方法
或者,如果您想使用“ then”回调,请尝试以下操作:
final collRef = Firestore.instance.collection('gameLevels');
DocumentReferance docReferance = collRef.document();
docReferance.setData(map).then((doc) {
print('hop ${docReferance.documentID}');
}).catchError((error) {
print(error);
});
Run Code Online (Sandbox Code Playgroud)
使用value.id,您可以在添加到 FireStore 后获取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"));
}
Run Code Online (Sandbox Code Playgroud)
@Doug Stevenson 是对的,调用 doc() 方法将返回您的文档 ID。(我使用的是 cloud_firestore 1.0.3)
要创建文档,您只需调用 doc()。例如,我想在将消息发送到 Firestore 之前获取消息 ID。
final document = FirebaseFirestore.instance
.collection('rooms')
.doc(roomId)
.collection('messages')
.doc();
Run Code Online (Sandbox Code Playgroud)
我可以打印并查看文档的 ID。
print(document.id)
Run Code Online (Sandbox Code Playgroud)
为了保存它而不是调用 add() 方法,我们必须使用 set()。
await document.set({
'id': document.id,
'user': 'test user',
'text': "test message",
'timestamp': FieldValue.serverTimestamp(),
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2741 次 |
| 最近记录: |