Flutter结合Firebase如何实现仅展示当前登录用户粉丝列表

问题说明
开发Flutter应用时需要实现当前登录用户的粉丝列表展示功能:Firebase已创建users集合,每个用户文档内存储用户ID、粉丝ID数组字段。现有代码运行后会加载展示全平台所有用户,无法实现仅展示当前登录用户粉丝的需求,需要调整代码。
核心错误点
FollowersScreen直接监听全量users集合数据,未做粉丝身份过滤,因此会加载所有平台用户FollowersCard代码结构错误:initState生命周期被错误嵌套在getdata方法内,且获取到的粉丝列表未赋值给对应变量,逻辑完全不生效;同时卡片内的查询逻辑属于冗余代码,父组件完成数据过滤后直接传入粉丝数据即可。
修改后代码
1. followers_screen.dart(粉丝列表页)
逻辑调整:先获取当前登录用户文档,拿到粉丝ID数组,再根据粉丝ID查询对应用户数据,过滤掉非粉丝用户;针对Firestore whereIn单次查询最多支持10个参数的限制,做分批查询处理。
class FollowersScreen extends StatefulWidget { const FollowersScreen({Key? key}) : super(key: key); @override State<FollowersScreen> createState() => _FollowersScreenState(); } class _FollowersScreenState extends State<FollowersScreen> { // 获取当前用户粉丝对应的用户数据列表 Stream<List<Map<String, dynamic>>> getFollowersStream() async* { final currentUserId = FirebaseAuth.instance.currentUser!.uid; // 监听当前用户的文档变化,实时同步粉丝列表更新 yield* FirebaseFirestore.instance .collection("users") .doc(currentUserId) .snapshots() .asyncMap((currentUserDoc) async { List<String> followerIds = List<String>.from(currentUserDoc.data()?['followers'] ?? []); if (followerIds.isEmpty) return []; // Firestore whereIn单次最多支持10个ID,分批查询避免报错 List<Map<String, dynamic>> followers = []; for (int i = 0; i < followerIds.length; i += 10) { final end = (i + 10 < followerIds.length) ? i + 10 : followerIds.length; final batch = await FirebaseFirestore.instance .collection("users") .where(FieldPath.documentId, whereIn: followerIds.sublist(i, end)) .get(); followers.addAll(batch.docs.map((e) => e.data()).toList()); } return followers; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: mobileBackgroundColor, centerTitle: true, title: Image.asset( 'Resim/logo.png', height: 50, ), ), body: StreamBuilder( stream: getFollowersStream(), builder: (context, AsyncSnapshot<List<Map<String, dynamic>>> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } // 粉丝列表为空时的提示 if (!snapshot.hasData || snapshot.data!.isEmpty) { return const Center(child: Text("暂无粉丝")); } return ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (context, index) => FollowersCard( snap: snapshot.data![index], ), ); }, ), ); } }
2. followers_card.dart(粉丝卡片组件)
逻辑调整:删除冗余的错误查询代码,直接使用父组件传入的粉丝用户数据渲染即可,补全类型定义避免运行时类型错误。
class FollowersCard extends StatefulWidget { final Map<String, dynamic> snap; const FollowersCard({ Key? key, required this.snap, }) : super(key: key); @override State<FollowersCard> createState() => _FollowersCardState(); } class _FollowersCardState extends State<FollowersCard> { @override Widget build(BuildContext context) { return Container( color: mobileBackgroundColor, child: Card( child: Column(children: [ // 粉丝信息头部 Container( padding: const EdgeInsets.symmetric( vertical: 4, horizontal: 16, ).copyWith(right: 0), child: Row( children: [ CircleAvatar( radius: 16, backgroundImage: NetworkImage( widget.snap['photoUrl'], ), ), Expanded( child: Padding( padding: EdgeInsets.only(left: 8), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.snap['username'], style: TextStyle(fontWeight: FontWeight.bold), ), ], ), ), ), ], ), ) ]), )); } }
注意事项
- 确保Firestore安全规则配置正确,已登录用户拥有读取
users集合的权限 - 如果后续需要在粉丝卡片上增加关注/取关按钮,直接在卡片组件内调用对应方法,操作当前用户的
following字段、对方用户的followers字段即可 - 代码已做空值兼容,
followers字段不存在或为空时不会触发空指针报错
内容的提问来源于stack exchange,提问作者user19490000
相关产品推荐
相关产品推荐

