flutter - Flutter Fire 中的 Firestore 动态查询

标签 flutter firebase google-cloud-platform google-cloud-firestore

我有一个内容集合,我想在某些情况下应用某些过滤器来检索它们。

我将过滤器值存储在 block 对象中,该值可以为空也可以不为空。如果它为空,则不应应用过滤器,如果它有值,则应用过滤器。

我想做这样的事情:

  CollectionReference contents =
    FirebaseFirestore.instance.collection('content');

  if (_bloc.searchQuery != null && _bloc.searchQuery.isNotEmpty) {
    // Add where criteria here
  }

  if (_bloc.publishUntilQuery != null) {
    // Add where criteria here
  }

  if (_bloc.publishFromQuery != null) {
    // Add where criteria here
  }

  return StreamBuilder<QuerySnapshot>(
    stream: contents.snapshots(),
    builder:
        (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      // ...
    },
  );

问题是我不知道如何构造诸如查询对象之类的东西以便稍后将其添加到最终搜索中。

如何解决这个问题?非常感谢。

最佳答案

doc 中所述,CollectionReference类继承自 Query类(class)。此外,Query 类中的方法用于优化查询(例如 orderBy()where() 等...)返回一个查询。因此,您可以使用这些不同的方法来优化您的初始查询,应用“特定情况下的特定过滤器”,如下所示:

  Query contents =
    FirebaseFirestore.instance.collection('content');

  if (_bloc.searchQuery != null && _bloc.searchQuery.isNotEmpty) {
    contents = contents.where('....', isEqualTo: '....');  // For example, to be adapted
  }

  if (_bloc.publishUntilQuery != null) {
    contents = contents.where('....', isEqualTo: '....');  // For example, to be adapted
  }

  if (_bloc.publishFromQuery != null) {
    contents = contents.where('....', isEqualTo: '....');  // For example, to be adapted
  }

  return StreamBuilder<QuerySnapshot>(
    stream: contents.snapshots(),
    builder:
        (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      // ...
    },
  );

关于flutter - Flutter Fire 中的 Firestore 动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65480934/

相关文章:

java - 使用 JAVA 数据存储中的自定义迭代器显示零

python - 如何在构造函数中使用 `this`?

flutter - 排除某些文件/库以在Flutter Web中构建

flutter - 如何更改 FLUTTER DropdownMenuItem 的 textDirection(更改小部件方向)

java - Flutter : Exception in thread "main" java.net.SocketException:连接重置

java - 如何在几次间隔后删除 Firebase 的最后一个条目?

javascript - 从 Firebase 获取初始集合值

wordpress - 全新安装 : httpd. 服务:未找到单元

Swift 和 Firebase | .timestamp() 的精确度如何,我可以用它作为标识吗?

google-cloud-platform - 我可以在不购买域名的情况下为我的 Google Cloud Storage 设置 MainPageSuffix 吗?