我正在使用 Flutter 制作应用程序,后端使用 Cloud Firestore。我有一个流,它检索所有用户的用户文档列表,并希望过滤最喜欢的食物是“意大利面”的用户。我不想加载其他文件。这是我的流,以及将其映射到我的用户模型的函数。
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('Users');``
List<MyAppUser> _userListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((DocumentSnapshot doc) {
return MyAppUser(
uid: doc.id ?? '',
name: (doc['name']).toString() ?? '',
email: (doc['email']).toString() ?? '',
favorite_food: (doc['favorite food']).toString() ?? '',
);
}).toList();
}
Stream<List<MyAppUser>> get users {
return usersCollection.snapshots().map(_userListFromSnapshot);
}
如果需要,这是我的用户模型:
class MyAppUser{
final String uid;
final String name;
final String email;
final String favorite_food;
MyAppUser({
this.name,
this.email,
this.uid,
this.favorite_food,
});
}
我应该在映射之后还是之前使用 where 函数?
如果我在映射之前过滤,我将不得不在原始流上做一个 where
usersCollection.where('favorite food', isEqualTo: 'pasta')
如果我在映射后过滤,我可以获得类型安全:
我用 Provider 收听流:final users = Provider.of<List<MyAppUser>>(context);
然后像这样查询:
users.where((user) => user.favorite_food == 'pasta');
我更喜欢使用类型安全,但是,我是否会因为只阅读过滤后的文档或所有文档而付费?