Flutter Firestore:如何获取列表中文档的ID



我正在努力弄清楚如何获得项目列表的id。我知道我可以获取单个文档并获取id,但对于列表,不知道该怎么做?下面我希望我的列表返回id以及每个ProductType

的名称
Future<List<ProductType>> getProductTypes() async {
var query = await collection.get();
return query.docs.map((e) => ProductType.fromJson(e.data())).toList();
}

ProductType.fromJson(Map<String, Object?> json) : this(
name: json["name"]! as String,
);

您可以使用QueryDocumentSnapshot.id属性来获取文档的id。

Future<List<ProductType>> getProductTypes() async {
var query = await collection.get();
return query.docs.map((e) => ProductType.fromJson({
"id": e.id,
"name": e.data()["name"]! as String,
})).toList();
}

https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/QueryDocumentSnapshot-class.html

最新更新