首页 > 解决方案 > Cloud Firestore 中的分页

问题描述

DocumentSnapshot如果提供到startAtstartAfter不起作用,我如何对数据进行分页。

在网络上,您可以使用以下内容

const first = db.collection('cities').orderBy('population').limit(25)

first.get().then(function (documentSnapshots) {
  // Get the last visible document.
  const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1]

  // Construct a new query starting at this document, get the next 25 cities.
  const next = db.collection('cities').orderBy('population').startAfter(lastVisible).limit(25)
})

另见:https ://github.com/flutter/flutter/issues/21017

标签: firebasedartfluttergoogle-cloud-firestore

解决方案


由于 Cloud Firestore 删除了此功能,因此不再有解决方法,即您无法再使用orderBy(FieldPath.documentID())

您目前不能将DocumentSnapshot用作参数。
但是,您可以简单地使用特定值。在此示例中,它将是文档中的population数字lastVisible

final db = Firestore.instance;    

db.collection('cities').orderBy('population').limit(25).getDocuments().then((querySnapshot) {
      final lastVisible = snapshot.documents.last;

      // Construct a new query starting at the last document, get the next 25 cities.
      final next = db.collection('cities').orderBy('population')
          .startAfter([lastVisible.data['population']]).limit(25);
    });

如果您有具有相同值的字段,则可以使用以下逻辑按文档 ID 排序:

.orderBy(...).orderBy('__name__').startAfter([..., lastVisible.documentId])


推荐阅读