Flutter Firestore中如何用多Where子句筛选多状态数据?
Fixing Firestore Query for Multiple Status Values
First, let's break down why your current code isn't working: when you chain multiple .where("status", isEqualTo: ...) clauses, Firestore looks for documents that match all those conditions at once. A single document can't have a status that's "confirmed", "unconfirmed", and "unconfirmed quotation" simultaneously—so your query returns no results.
The Correct Approach: Use whereIn
Firestore provides the whereIn operator to filter documents where a field matches any value in a list. Here's how to adjust your code:
Stream<QuerySnapshot> getStream() { return FirebaseFirestore.instance .collection("booking") .where("userId", isEqualTo: uid) .where("status", whereIn: ["confirmed", "unconfirmed", "unconfirmed quotation"]) .snapshots(); }
Key Notes:
whereInaccepts a list of values to match against the "status" field.- Firestore limits
whereInlists to 10 elements—which is more than enough for your 3 status values. - This query will return all booking documents for the specified
uidwhere the status is one of the three values you listed.
Example: Using the Stream in a Widget
To display this data in your Flutter app, you'd typically use a StreamBuilder to react to real-time updates:
StreamBuilder<QuerySnapshot>( stream: getStream(), builder: (context, snapshot) { if (snapshot.hasError) { return const Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } return ListView( children: snapshot.data!.docs.map((DocumentSnapshot document) { Map<String, dynamic> data = document.data()! as Map<String, dynamic>; return ListTile( title: Text(data['status']), // Add other fields from your document to display here ); }).toList(), ); }, )
Additional Tips
- If you ever need to match more than 10 values, you'll have to split your query into multiple requests and combine the results (since
whereInhas a hard 10-value limit). - Ensure your Firestore security rules allow read access to the "booking" collection for the authenticated user (matching the
uidyou're filtering with).
内容的提问来源于stack exchange,提问作者Jithin Joy
相关产品推荐
相关产品推荐

