当我在我的 flutter 应用程序中使用 cloud firestore 时,发生了奇怪的异常。
已编辑
这是我的代码 :
Stream<List<Product>> productsStream(int id) async* {
final k = _db
.collection('products')
.where('category_id', isEqualTo: id)
.where('stock', isGreaterThanOrEqualTo: 1)
.orderBy('order')
.snapshots();
yield* k.map((event) => event.docs
.map((e) => Product.fromJson(
e.data(),
))
.toList());
在这里我想要实现的是检查产品是否有库存和然后 按升序订购产品 order
我的领域 products
收藏。但我收到这个奇怪的错误:
Exception: 'package:cloud_firestore/src/query.dart': Failed assertion: line 421 pos 16: 'field == orders[0][0]': The initial orderBy() field '[[FieldPath([order]), false]][0][0]' has to be the same as the where() field parameter 'FieldPath([stock])' when an inequality operator is invoked.
什么可能是解决方案?
最佳答案
这在 ordering limitations documentation 中有解释:
If you include a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field
所以我怀疑你应该有:
.where('category_id', isEqualTo: id)
.where('stock', isGreaterThanOrEqualTo: 1)
.orderBy('stock')
.orderBy('order')
显然,这意味着它不再主要由 order
订购。 .如果这是一个问题,您需要进行本地排序 - 在这种情况下,您可能会发现根本不想订购服务器端。虽然文档中没有提到“不等于”过滤器,但听起来它们在禁止过滤方面也算作范围比较。
所以基本上,我建议你要么需要在
stock
上本地过滤, 或者您需要在 order
本地订购- 您目前无法在同一个 Firestore 查询中同时执行这两项操作。请注意,此服务器端限制在 future 可能会发生变化(对于所有范围比较,或者可能只是允许“不等于”),因此可能值得定期重新测试。
关于firebase - Cloud Firestore 不等式运算符异常抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66829643/