【问题标题】:Dart streams (Flutterfire): Should I use the where filter before or after mapping?Dart 流 (Flutterfire):我应该在映射之前还是之后使用 where 过滤器?
【发布时间】:2021-08-26 02:46:38
【问题描述】:

我正在使用 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&lt;List&lt;MyAppUser&gt;&gt;(context); 然后像这样查询:

users.where((user) => user.favorite_food == 'pasta');

我更喜欢使用类型安全,但是,我是否会因为只阅读过滤后的文档或所有文档而付费?

【问题讨论】:

    标签: flutter dart google-cloud-firestore google-cloud-billing dart-stream


    【解决方案1】:

    在对their article on medium.com 发表评论后,我从Aurimas Deimantas 得到了这个答案。下面,我调整了他们的答案以适应这个问题。


    Firestore 根据您的文档阅读量向您收费。

    在映射之前过滤会更好,用

    usersCollection.where('favorite food', isEqualTo: 'pasta')
    

    因为这将只读取最喜欢的食物是面食的文档

    如果你在 映射之后过滤,像这样:

    users.where((user) => user.favorite_food == 'pasta');
    

    然后将读取所有用户文档,然后过滤。因此,Firestore 会为您读取的所有文档计费,而不仅仅是那些最喜欢的食物是意大利面的人。

    这就是为什么在将userscollection 映射到您的模型之前直接过滤它可以节省资金的原因。

    如果您想将流映射到您的模型,您可以在where 过滤器之后进行,方法是在.where(...) 函数之后添加.map(...) 函数,这将映射(并读取)仅通过 where 过滤器的文档,从而节省资金。

    【讨论】:

      【解决方案2】:

      你可以在集合调用之后使用 where 子句

      ... Collection('Users').where(field, conditions) 有了这个,你就没有使用集合的过滤器列表

      【讨论】:

      • 但是我想做很多过滤器,所以我做了一个集合引用,以便我可以重复使用它。另外,有没有办法做到类型安全?
      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      相关资源
      最近更新 更多