dart flutter-firestore错误java. lang.非法参数异常:无效查询

im9ewurl  于 2023-03-05  发布在  Flutter
关注(0)|答案(1)|浏览(112)

我有这个代码片段来查询firestore:

FirebaseTransactionRepository(this.userId) : transactionCollection = firestore.FirebaseFirestore.instance.collection('users').doc(userId).collection('transactions');
   var query = transactionCollection.orderBy('created_date', descending: transactionQuery.sortOrder == SortOption.Newest);

    if (transactionQuery.fromDate != null) {
      query = transactionCollection.where('created_date', isGreaterThanOrEqualTo: transactionQuery.fromDate);
    }
    if (transactionQuery.toDate != null) {
      query = transactionCollection.where('created_date', isLessThanOrEqualTo: transactionQuery.toDate);
    }
    if (transactionQuery.lastDocument != null) {
      query = query.startAfterDocument(transactionQuery.lastDocument!);
    }
    return query.limit(transactionQuery.limit).get().then((snapshot) {
      final List<Transaction> transactions = snapshot.docs.map((doc) => Transaction.fromEntity(TransactionEntity.fromSnapshot(doc))).toList();
      firestore.DocumentSnapshot? lastDocument;
      if (snapshot.docs.isNotEmpty) {
        lastDocument = snapshot.docs.last;
      }
      return TransactionQueryResult(transactions: transactions, query: transactionQuery.copyWith(lastDocument: lastDocument));
    });

然而,这给我以下错误:
java. lang.非法参数异常:查询无效。您在字段"created_date"上有不等式where筛选器(whereLessThan()、whereGreaterThan()等),因此您还必须将"created_date"作为第一个orderBy()字段,但第一个orderBy()当前位于字段"name"上。
让我感到奇怪的是,我已经将created_date用于我的第一个也是唯一的orderBy,我不确定字段'name'在这里是如何关联的。

46qrfjad

46qrfjad1#

好吧,我可以通过改变语句的顺序来解决这个问题:

firestore.Query<Object?> query;
    if (transactionQuery.contactIDs != null && transactionQuery.contactIDs!.isNotEmpty) {
      query = transactionCollection.where('cid', whereIn: transactionQuery.contactIDs);
    }
    if (transactionQuery.fromDate != null) {
      query = transactionCollection.where('created_date', isGreaterThanOrEqualTo: transactionQuery.fromDate);
    }
    if (transactionQuery.toDate != null) {
      query = transactionCollection.where('created_date', isLessThanOrEqualTo: transactionQuery.toDate);
    }
    query = transactionCollection.orderBy('created_date', descending: transactionQuery.sortOrder == SortOption.Newest);

orderBy应在where方法之后使用)

相关问题