首页 > 解决方案 > Flutter & Firestore:如何首先获得最新的?

问题描述

如何从 Firestore 获取最新的第一个?

FirebaseFirestore.instance.collection(Strings.factsText)
                .where(
                    Strings.category,
                    whereIn: [Strings.climateChange])
                    .orderBy('timestamp', descending: true)
                    .snapshots(),
               
                    ...
                  final factsDocs = snapshot.data.documents;
                  return FactsListContainer(factsDocs: factsDocs);
                });

.where使用 with 时,问题似乎出在with .orderBy

标签: firebasefluttergoogle-cloud-firestore

解决方案


如果您有一个createdAt带有时间戳的字段,或者一个始终递增的值,您可以按该字段的降序获取快照:

stream: FirebaseFirestore.instance
  .collection(Strings.factsText)
  .orderBy('timestamp', descending: true)
  .where(
    Strings.category,
    whereIn: [Strings.climateChange])
    .snapshots(),

Query.orderBy另请参阅有关方法的 FlutterFire 文档。


推荐阅读