0

I need to merge two queries into one and return a Future<QuerySnapshot>. My code is not merging query2 into query1, it is only returning docs in query1. Code below:

Future<QuerySnapshot> mergeQueries() async {
    QuerySnapshot query1 = await FirebaseFirestore.instance
        .collection('practice')
        .orderBy('timeStamp', descending: true)
        .where('teamId', isEqualTo: widget.teamId)
        .where('checkSinglesDoubles', isEqualTo: dropDownType)
        .where('player1name', isEqualTo: playerNameFilter)
        .get();

    QuerySnapshot query2 = await FirebaseFirestore.instance
        .collection('practice')
        .orderBy('timeStamp', descending: true)
        .where('teamId', isEqualTo: widget.teamId)
        .where('checkSinglesDoubles', isEqualTo: dropDownType)
        .where('player2name', isEqualTo: playerNameFilter)
        .get();

    query1.docs.addAll(query2.docs);

    return query1;
    }
jraufeisen
  • 3,005
  • 7
  • 27
  • 43

1 Answers1

1

The docs property of a QuerySnapshot object is read-only, so calling query1.docs.addAll(query2.docs) has no effect.

There is no way to combine two queries (or their corresponding query snapshots) into one. This makes sense - since on the server side Firestore does not support logically compound queries in general.

What you could could do instead is to extract the documents (or the data they contain) from the QuerySnapshots and combine those with each other. This will change your return type, but provide the functionality you were looking for.

Future<QueryDocumentSnapshot<T>> mergeQueries() async {
  var query1 = await ...;
  var query2 = await ...;

  var combinedDocs = query1.docs;
  combinedDocs.addAll(query2.docs);
  return combinedDocs;
}
jraufeisen
  • 3,005
  • 7
  • 27
  • 43