Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Cloud FireStore query using multiple conditional where clauses

I have been struggling with the correct way to perform a query with multiple conditional queries based on some criteria that may or may not be added. I have tried several ways but it's not working.

Future<QuerySnapshot> searchStuff(StuffModel stuff) async {

    CollectionReference col = _firestore.collection(Constants.stuffCollection);

    Query query = col.where('uid', isEqualTo: stuff.uid);

    if (stuff.who != null) {
      query = query.where('who', isEqualTo: stuff.who);
    }
    if (stuff.what != null) {
      query = query.where('what', isEqualTo: stuff.what);
    }
    if (stuff.where != null) {
      query = query.where('where', isEqualTo: stuff.where);
    }
    if (stuff.when != null) {
      query = query.where('when', isEqualTo: Timestamp.fromDate(stuff.when));
    }

    return await query.getDocuments();
  }
like image 512
Daniel Ortiz Avatar asked Sep 03 '25 01:09

Daniel Ortiz


1 Answers

After adding additional evaluation, for not empty values, on each condition, the code now looks like this and is working fine:

Future<QuerySnapshot> searchStuff(StuffModel stuff) async {

    CollectionReference col = _firestore.collection(Constants.stuffCollection);

    Query query = col.where('uid', isEqualTo: stuff.uid);

    if (stuff.who != null && stuff.who.isNotEmpty) {
      query = query.where('who', isEqualTo: stuff.who);
    }
    if (stuff.what != null && stuff.what.isNotEmpty) {
      query = query.where('what', isEqualTo: stuff.what);
    }
    if (stuff.where != null && stuff.where.isNotEmpty) {
      query = query.where('where', isEqualTo: stuff.where);
    }
    if (stuff.when != null) {
      query = query.where('when', isEqualTo: Timestamp.fromDate(stuff.when));
    }
    return await query.getDocuments();
}
like image 52
Daniel Ortiz Avatar answered Sep 05 '25 23:09

Daniel Ortiz