Flutter Fire 中的 Firestore 动态查询

svp*_*dga 2 firebase google-cloud-platform flutter google-cloud-firestore

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

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

我想做这样的事情:

  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) {
      // ...
    },
  );
Run Code Online (Sandbox Code Playgroud)

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

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

Ren*_*nec 5

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

  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) {
      // ...
    },
  );
Run Code Online (Sandbox Code Playgroud)