Flutter StreamBuilder中Firestore同时使用where与orderBy查询无数据返回问题
It sounds like you're hitting a common Firestore gotcha here: missing composite indexes. Let’s break down why your code is behaving this way and how to fix it:
Why This Happens
When you combine multiple where filters with an orderBy clause, Firestore requires a composite index to efficiently run the query. Without this index:
- Offline mode (using local cache) might work temporarily because Firestore can handle simple queries locally. But once your app syncs with the remote database, the query fails silently (returning no results).
- The brief appearance of tasks (on hot reload, restart, or adding a new task) happens because your local cache shows the data first. But once the remote query fails, the stream updates to reflect the empty server response, making the tasks disappear.
How to Fix It
Step 1: Use the Auto-Generated Index Link
Firebase will log a direct link to create the required index when your query fails. Check your Flutter debug console for a message like this:
The query requires an index. You can create it here: [Firebase Console index creation link]
Click that link, sign into your Firebase account, and follow the prompts to create the index. It usually takes 1-2 minutes to build, but once it’s done, your query should work as expected.
Step 2: Manually Create the Index (If Needed)
If you don’t see the auto-generated link, you can create the index manually in the Firebase Console:
- Go to your Firebase project → Firestore Database → Indexes → Composite Indexes.
- Click Add Index.
- Select your collection (the one named after the user’s email).
- Add the fields in this order:
completed(ascending order)expired(ascending order)DOC(ascending order, since yourorderByusesdescending: false)
- Give the index a name (optional) and click Create.
Step 3: Double-Check Your Setup
Quickly verify a few things to rule out other issues:
- Ensure field names (
completed,expired,DOC) exactly match what’s stored in Firestore (they’re case-sensitive!). - Confirm
completedandexpiredare stored as booleans (not strings or numbers) in your documents. - Make sure your Firestore security rules allow the user to read from this collection (since you can add data successfully, this is probably okay, but it’s worth a quick check).
Testing the Fix
Once the index finishes building, restart your app. Your StreamBuilder should now correctly filter and order active tasks without them disappearing.
Content of the question originates from Stack Exchange, asked by Okafor Onyekachukwu




