Flutter Firebase:无需模型从Firestore读取指定字段为列表
从Firestore的device集合提取id字段值组成列表(无需模型)
完全可以不用模型实现,直接通过遍历查询快照、提取字段值的方式就能得到你想要的纯id列表,以下是不同平台的具体实现:
Flutter/Dart 实现
Future<List<String>> getDeviceIds() async { // 获取device集合的所有文档快照 QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('device').get(); // 遍历每个文档,提取数据中的id字段,过滤空值后转为列表 return snapshot.docs .map((doc) => doc.data()?['id'] as String?) .where((id) => id != null) .cast<String>() .toList(); }
如果你的id是Firestore自动生成的文档ID(而非文档数据里的字段),直接提取doc.id即可:
Future<List<String>> getDeviceIds() async { QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('device').get(); return snapshot.docs.map((doc) => doc.id).toList(); }
JavaScript/Web 实现
async function getDeviceIds() { const querySnapshot = await firebase.firestore().collection('device').get(); // 遍历文档,提取数据中的id字段并收集 return querySnapshot.docs .map(doc => doc.data().id) .filter(id => id != null && id !== undefined); }
若要提取Firestore自动生成的文档ID,代码更简洁:
async function getDeviceIds() { const querySnapshot = await firebase.firestore().collection('device').get(); return querySnapshot.docs.map(doc => doc.id); }
注意事项
- 上述代码都直接操作Firestore返回的原始Map数据,无需定义任何模型类或数据结构
- 加入空值过滤是为了避免列表中混入无效数据,若能确保所有文档都有
id字段,可去掉filter部分
内容的提问来源于stack exchange,提问作者x98lol
相关产品推荐
相关产品推荐

