Flutter Firestore技术问题:如何获取列表中文档的ID
解决方法
Firestore文档的ID并不包含在e.data()返回的JSON数据里,它存在于文档快照的id属性中。要让每个ProductType同时包含ID和名称,你需要做以下两步修改:
1. 更新ProductType模型
给ProductType添加id字段,同时调整构造函数(推荐新增一个从文档快照直接创建实例的构造函数,更直观):
class ProductType { final String id; final String name; ProductType({required this.id, required this.name}); // 新增从文档快照创建实例的构造函数,直接获取ID和名称 ProductType.fromDocumentSnapshot(DocumentSnapshot doc) : id = doc.id, name = doc.data()!["name"] as String; // 若需保留原fromJson方法,需补充id参数 ProductType.fromJson(Map<String, Object?> json, {required String id}) : id = id, name = json["name"]! as String; }
2. 修改getProductTypes方法
遍历文档快照时,将文档ID传递给ProductType的构造函数:
方式一:使用新增的fromDocumentSnapshot(推荐)
Future<List<ProductType>> getProductTypes() async { var query = await collection.get(); return query.docs.map((e) => ProductType.fromDocumentSnapshot(e)).toList(); }
方式二:使用原fromJson方法传递ID
Future<List<ProductType>> getProductTypes() async { var query = await collection.get(); return query.docs.map((e) => ProductType.fromJson(e.data(), id: e.id)).toList(); }
修改完成后,你获取到的ProductType列表中每个对象都会包含对应的文档ID和名称。
内容的提问来源于stack exchange,提问作者Primico
相关产品推荐
相关产品推荐

