我有一个内容的集合,我想在某些情况下应用某些过滤器来检索它们。
我将滤镜的值存储在一个bloc对象中,这个值可以是空的,也可以不是。如果为null,则不应应用筛选器,如果它有值,则应用筛选器。
我想做这样的事情:
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) {
// ...
},
);问题是我不知道如何构造查询对象这样的东西,以便稍后将其添加到最终搜索中。
如何解决这个问题?非常感谢。
发布于 2020-12-29 01:58:07
正如doc中所解释的,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) {
// ...
},
);https://stackoverflow.com/questions/65480934
复制相似问题