首页 > 解决方案 > 从 Firestore 获取数据

问题描述

所以我使用 Firebase 从 firestore 检索数据,这工作正常,但现在为了节省金钱和资源,我使用了 40 个项目的限制,所以只有 40 个项目来自 firebase,但现在当用户到达列表末尾我希望用户能够从 firebase 数据库中获取接下来的 40 个项目。这就是我不知道该怎么做。要获得接下来的 40 项,而无需从 firebase 读取全部 80 项。

这是我的代码:

getCountryItems() async{
      QuerySnapshot snapshot = await userCountry
      .orderBy('timeStamp', descending: true)
      .limit(40) //getting only 40 items
      //.orderBy('likesCount', descending: true)
      .getDocuments();

      List<Items> countryPosts = snapshot.documents.map((doc) => Items.fromDocument(doc)).toList();
      setState(() {
        this.countryPosts = countryPosts;
      });
     }

所以这就是获得前 40 个项目的原因,现在我只想在按下按钮后获得 40 个项目:

FlatButton(
 onPressed: (){}//funtion to get the next 40 items 
);

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


参考:https
: //firebase.google.com/docs/firestore/query-data/query-cursors 使用 startAfter 将光标移动到所需位置

getCountryItems(paginateAt = 0) async{
      QuerySnapshot snapshot = await userCountry
      .orderBy('timeStamp', descending: true)
      .startAfter(paginateAt)
      .limit(40) //getting only 40 items
      //.orderBy('likesCount', descending: true)
      .getDocuments();

      List<Items> countryPosts = snapshot.documents.map((doc) => Items.fromDocument(doc)).toList();
      setState(() {
        this.countryPosts = countryPosts;
      });
     }

FlatButton(
 onPressed: (){
   getCountryItems(this.countryPosts.last)
 }//funtion to get the next 40 items 
);


推荐阅读