简体   繁体   English

如何使用 .where(GreaterThan, and LessThan) 条件从 firestore 获取数据。 - 颤振

[英]How to fetch data from firestore using .where(GreaterThan, and LessThan) condition. - Flutter

I'm trying to fetch data from firestore using the .where() condition.我正在尝试使用.where()条件从 firestore 获取数据。

 Query adsRef = FirebaseFirestore.instance
    .collection('All ads')        
    .where('adPrice',
        isGreaterThanOrEqualTo: '2000') 
    .where('adPrice',
        isLessThanOrEqualTo: '115000') 
    .limit(adsPerPage);
QuerySnapshot querySnapshot = await adsRef.get();

When using only one condition (eg: .where('adPrice',isGreaterThanOrEqualTo: '2000') ) works but dosen't fetch all documents[Just fetching random documents].当仅使用一种条件时(例如: .where('adPrice',isGreaterThanOrEqualTo: '2000') )有效但不会获取所有文档[只是获取随机文档]。
And when using both condtions it retruns null even though the DB has matching data.并且在使用这两种条件时,即使数据库具有匹配数据,它也会返回 null。

Is there any other way to fetch data from firestore within two numbers?有没有其他方法可以从两个数字内的 firestore 中获取数据? (in between 2000 to 115000) (在 2000 年至 115000 年之间)

Two inequality conditions are not valid in one firestore query.两个不等式条件在一个 firestore 查询中无效。 wrap you block of code in try catch and you will see the error.在 try catch 中包装你的代码块,你会看到错误。

Alternatively you can query both of your conditions separately and then merge the results like this:或者,您可以分别查询您的两个条件,然后像这样合并结果:

void getAds() async {
    List<Future<QuerySnapshot>> futures = [];
    var firstQuery = FirebaseFirestore.instance
.collection('All ads')
        .where('adPrice', isGreaterThanOrEqualTo: '2000')
        .getDocuments();
var secondQuery = FirebaseFirestore.instance
.collection('All ads')
        .where('adPrice', isLessThanOrEqualTo: '115000')
        .getDocuments();

    futures.add(firstQuery);
    futures.add(secondQuery);

    List<QuerySnapshot> results = await Future.wait(futures);
    results.forEach((res) {
      res.documents.forEach((docResults) {
        print(docResults.data);
      });
    });
  }

Please do try this and let me know if it works for you.请试试这个,让我知道它是否适合你。 Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM