【发布时间】:2021-09-17 16:45:25
【问题描述】:
如何在flutter(在本例中为flutter web)上使用firestore流正确实现分页? 我目前使用 bloc 的方法很可能是错误的,就像这样
加载下一页时在 bloc 上调用的函数,请注意,每次调用该函数时,我都会将 state 的 lastPage 变量增加 1:
Stream<JobPostingState> _loadNextPage() async* {
yield state.copyWith(isLoading: true);
try {
service
.getAllDataByClassPage(state.lastPage+1)
.listen((List<Future<DataJob>> listDataJob) async {
List<DataJob?> listData = [];
await Future.forEach(listDataJob, (dynamic element) async {
DataJob data= await element;
listData.add(data);
});
bool isHasMoreData = state.listJobPostBlock.length!=listData.length;
//Update data on state here
});
} on Exception catch (e, s) {
yield StateFailure(error: e.toString());
}}
调用函数来获取流数据
Stream<List<Future<DataJob>>> getAllDataByClassPage(
String className, int page) {
Stream<QuerySnapshot> stream;
if (className.isNotEmpty)
stream = collection
.orderBy('timestamp', "desc")
.where('class', "==", className).limit(page*20)
.onSnapshot;
else
stream = collection.onSnapshot;
return stream.map((QuerySnapshot query) {
return query.docs.map((e) async {
return DataJob.fromMap(e.data());
}).toList();
});
}
使用这种方法,它可以按预期工作,当我加载下一页并仍在收听流时加载的数据增加,但我不知道这是否是正确的方法,因为它替换了流,它可能会读取数据两次并结束与不使用分页相比,我对 Firestore 的阅读次数要多得多。非常感谢任何建议,谢谢。
【问题讨论】:
标签: flutter dart google-cloud-firestore stream