使用多个条件where子句的Flutter Cloud FireStore查询

时间:2019-06-29 20:07:07

标签: firebase flutter google-cloud-firestore

我一直在努力尝试根据可能会添加或可能不会添加的一些条件对多个条件查询执行查询的正确方法。我已经尝试了几种方法,但是没有用。

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();
  }

1 个答案:

答案 0 :(得分:0)

在添加附加评估后,对于每种条件,对于非空值,代码现在看起来都像这样,并且可以正常工作:

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();
}