Firebase中的查询限制- . orderby()错误



我正在尝试使用此方法从Firebase的集合中获取数据:

FirebaseFirestore.instance.collection('posts')                      
.where('datePublished', isGreaterThanOrEqualTo: 1)
.orderBy('datePublished')
.orderBy('votes', descending: true)

问题是帖子现在按'datePublished'排序,但我希望帖子列表按'votes'排序。

如果我删除.orderBy('datePublished')行,我将收到这个错误(这里是该错误消息的文档参考,如果它可以提供更多帮助):

error 'package:cloud_firestore/src/query.dart': Failed assertion: line 487 pos 13: 'conditionField == orders[0][0]': The initial orderBy() field "[[FieldPath([votes]), true]][0][0]" has to be the same as the where() field parameter "FieldPath([datePublished])" when an inequality operator is invoked. #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)

任何帮助感激,谢谢!

尝试以下代码:

Stream<List<T>> collectionStream<T>({
required String path,
required T Function(Map<String, dynamic> data, String documentId) builder,
Query<Object?> Function(Query query)? queryBuilder,
bool Function(T)? where,
}) {
Query<Object?> query = firestore.collection(path);
if (queryBuilder != null) {
query = queryBuilder(query);
}
Stream<QuerySnapshot<Object?>> snapshots = query.snapshots();
return snapshots.map((snapshot) {
List<T> result = snapshot.docs.map((snapshot) => builder(snapshot.data() as Map<String, dynamic>, snapshot.id)).where((value) => value != null).toList();
if (where != null) {
result.where(where);
}
return result;
});
}

class Model {
Model(this.id, this.datePublished, this.votes);
final String id;
final int datePublished;
final int votes;
factory Model.fromMap(Map<String, dynamic> data, String documentId) {
final String? datePublished = data["datePublished"];
final String? votes = data["votes"];
return Model(documentId, datePublished ?? 0, votes ?? 0);
}
Map<String, dynamic> toMap() => {"datePublished": datePublished, "votes": votes};
}

collectionStream(
path: "posts",
queryBuilder: (query) => query.orderBy('votes', descending: true),
builder: (data, documentId) => Model.fromMap(data, documentId),
where: (model) => model.datePublished >= 94,
),

最新更新