如何获取Firebase自动生成的随机文档ID?
获取Firebase自动生成的文档ID
你的代码目前只提取了文档的内容数据(doc.data()),但Firebase自动生成的随机ID是文档对象本身的属性,存储在doc.id中,不属于文档数据字段的一部分。
要获取这个ID,只需要在遍历文档时把doc.id传递给你的News模型即可,具体修改如下:
修改后的数据流代码
newsCollection .doc('dunya') .collection('haberler') .snapshots() .map((snapshot) { return snapshot.docs.map((doc) { // 将文档ID和数据一起传入模型构造方法 return News.fromFirestore(doc.data(), doc.id); }).toList(); });
调整News类实现
需要同步修改News类的工厂方法,让它能接收并存储文档ID:
class News { final String id; // 你的其他业务字段,示例如下 final String title; final String content; News({required this.id, required this.title, required this.content}); // 更新fromFirestore方法,新增id参数 factory News.fromFirestore(Map<String, dynamic> data, String id) { return News( id: id, title: data['title'] ?? '', content: data['content'] ?? '', // 其他字段按实际数据映射即可 ); } }
如果你的News类原本有不同的构造方式,只要保证把doc.id传递到模型中并完成属性赋值,就能拿到目标ID了。
内容的提问来源于stack exchange,提问作者Farid Ahmadov
相关产品推荐
相关产品推荐

