Flutter使用Firestore的whereIn查询超10个元素报错如何解决?
解决方案
核心思路
Firestore的whereIn查询存在单次最多传入10个对比值的官方硬限制,可通过分片查询的方式解决该问题:
- 将长关注列表按每10个元素为一组拆分为多个子列表
- 对每个子列表单独发起
whereIn查询,通过Future.wait并行执行所有查询提升效率 - 合并所有查询返回的文档数据,统一生成UserTicket列表
修改后的完整代码
import 'dart:math'; buildFollowingTickets() { if (widget.followingList.isNotEmpty) { // 1. 将关注列表拆分为每10个元素一组的分片 final followChunks = <List<String>>[]; for (int i = 0; i < widget.followingList.length; i += 10) { int end = min(i + 10, widget.followingList.length); followChunks.add(widget.followingList.sublist(i, end)); } // 2. 为每个分片生成查询Future,并行执行所有查询 final queryFutures = followChunks.map((chunk) => userRef.where('id', whereIn: chunk).get()).toList(); return FutureBuilder( future: Future.wait(queryFutures), builder: (context, AsyncSnapshot<List<QuerySnapshot>> snapshot) { if (!snapshot.hasData) { return loading(); } // 3. 合并所有查询返回的文档 final allFollowDocs = snapshot.data!.expand((querySnap) => querySnap.docs).toList(); List<UserTicket> userFollowing = []; for (var following in allFollowDocs) { final data = following.data() as Map<String, dynamic>; final id = data['id']; final displayName = data['displayName']; final photoUrl = data['photoUrl']; final UserTicket userTicket = UserTicket( displayName: displayName, photoUrl: photoUrl, id: id, ); userFollowing.add(userTicket); } return ListView( children: userFollowing, ); }, ); } // 关注列表为空时返回空占位 return const SizedBox.shrink(); }
补充说明
如果需要UserTicket的顺序和原关注列表顺序一致,可以在合并完所有UserTicket后,按照原widget.followingList的顺序对userFollowing列表做一次排序即可。
内容的提问来源于stack exchange,提问作者MatanB
相关产品推荐
相关产品推荐

