繁体   English   中英

使用分页时如何从最新到最旧查询 firestore 集合?

[英]how to query a firestore collection from latest to the oldest when using pagination?

我正在查询一个 firestore 集合并使用flutterfire's FirestoreQueryBuilder进行分页,它应该一次每页查询 10 个文档。

这是我的 Firestore 系列:

在此处输入图像描述

我需要的是从最新的数据到最旧的查询 最新的在底部,最旧的在顶部。

问题是查询 firestore 集合总是从顶部开始。 即使您将按日期排序查询,如下所示: query.where(something).orderBy('date', descending: true) 这样做是从顶部获取前 10 个文档,然后按日期排序,这不是我想要的。

所以问题是我们如何查询自下而上的 firestore 集合,以便我可以获得第一个最新的 10 个文档?

或者我在想的另一件事是我们可以颠倒 firestore 收集的顺序吗? 那如果我们添加一个文件,它应该把append推到最上面而不是推到最下面? 这可能吗?

这是我查询 firestore 集合的代码:

 Query<T> collectionQuery<T>({ required String path, required T Function(DocumentSnapshot<Map<String, dynamic>> snapshot, SnapshotOptions? options) fromMap, required Map<String, Object?> Function(T, SetOptions? options) toMap, Query<T> Function(Query<T>? query)? queryBuilder, }) { Query<T> query = firestore.collection(path).withConverter<T>(fromFirestore: fromMap, toFirestore: toMap); if (queryBuilder;= null) { return query = queryBuilder(query); } else { return query; } }

下面是我如何使用 FirestoreQueryBuilder 来显示集合:

 return FirestoreQueryBuilder<T>( pageSize: pageSize, query: query, builder: (context, snapshot, ___) { if (snapshot.isFetching) { return loading?? const Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center( child: Text( snapshot.error.toString(), style: Styles.k16Bold, ), ); } if (snapshot.docs.isEmpty) { return emptyWidget?? const Center( child: Text( 'No item found', style: Styles.k18Grey, )); } return ListView.separated( padding: padding?? const EdgeInsets.all(0), physics: const BouncingScrollPhysics(), shrinkWrap: true, controller: listController, reverse: reverListView, itemCount: snapshot.docs.length, separatorBuilder: (_, __) => separator, itemBuilder: ((context, index) { if (snapshot.hasMore && index + 1 == snapshot.docs.length) { // Tell FirestoreQueryBuilder to try to obtain more items. // It is safe to call this function from within the build method. if (connection) { snapshot.fetchMore(); } } final list = reverseItems? snapshot.docs.reversed.toList(): snapshot.docs; print('list: ${list.length}'); if (sort.= null) { final item = list[index];data(). list;sort(sort), return itemBuilder(item; index). } else { final item = list[index];data(), return itemBuilder(item; index), } }); ), }; );

尝试类似的东西

final query = FirebaseFirestore.instance.collection('users')
                  .orderBy("timestamp")
                  .limit(10);

这将为您提供最新数据位于底部而最旧数据位于顶部的结果。

暂无
暂无

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

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