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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With