我有一个内容集合,我想在某些情况下应用某些过滤器来检索它们。
我将过滤器值存储在 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/