首页 > 解决方案 > 如何使用 orderBy() 和 Where() 相同?(颤振网络)

问题描述

不加载数据,但它会无限加载♾如果我取消 OrderBy 那么它可以工作,但我需要 Order by

代码:

body: StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance
          .collection("crush")
          .where("user", isEqualTo: user.email)
          .orderBy("date", descending: true)
          
          .snapshots(),
      builder:
          (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) {

标签: flutter

解决方案


当您执行这样的复合查询时,您需要创建复合索引。有两种方法可以为其创建索引:

使用错误消息创建索引:


当您尝试使用没有现有索引的复合查询时,您将在调试控制台中收到如下错误:

E/flutter (23618): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常: [cloud_firestore/failed-precondition] 查询需要索引。You can create it here: https://console.firebase.google.com/v1/r/project/yourprojectname/firestore/indexes?create_composite=Ck1wcm9qZWN0cy92b2lkY2hhdGJldGEvZGF0YWJhc2VzLyhkZWZhdWx0KS9jb2xsZWN0aW9uR3JvdXBzL2NvbnRhY3RzL2luZGV4ZXMvXxABGgsKB3VzZW5hbWUQARoGCgJpZBABGgwKCF9fbmFtZV9fEAE

此错误具有使用Firebase 控制台创建缺失索引的链接。按照此链接,检查数据并单击创建

使用 Firebase 控制台手动创建索引:


  • 转到索引选项卡,然后单击创建索引
  • Enter the collection name and set the fields you want to order the index by.

For non-array and non-map fields, you must select ascending or descending ordering, even if you don't need the field for ordering. Your choice doesn't impact the behavior of equalities in the query.

  • Click Create.

推荐阅读