Flutter中向Firebase Firestore添加帖子时如何获取自动生成的文档ID
解决Firestore自动生成文档ID并存储到字段的问题
你可以通过**先获取文档引用(此时已生成自动ID)**再写入数据的方式实现,无需自行生成ID。具体操作如下:
- 先创建不带参数的
doc()引用,Firestore会自动为该引用生成唯一ID - 从引用中提取
id属性,作为postid字段的值 - 调用该引用的
set()方法写入完整数据
修改后的代码如下:
IconButton(onPressed: () async { // 先创建文档引用,自动生成唯一ID final postDocRef = FirebaseFirestore.instance.collection("posts").doc(); await postDocRef.set({ 'message': txtpost.text, 'postby': FirebaseAuth.instance.currentUser!.email, 'posttime': Timestamp.now(), 'likes': [], 'postid': postDocRef.id // 直接获取Firestore自动生成的文档ID }); print('Post Added Successfully...'); txtpost.clear(); }, icon: Icon(Icons.send))
这种方式的优势:
- 完全复用Firestore内置的ID生成逻辑,无需自己处理ID唯一性问题
- 确保存储的
postid和文档实际ID完全一致,避免后续查询、关联数据时出现不一致情况
内容的提问来源于stack exchange,提问作者Irfan Ganatra
相关产品推荐
相关产品推荐

