Flutter中如何实现关注按钮二次点击切换回未关注状态?
实现步骤
1. 调整按钮点击的状态切换逻辑
你当前只在点击时把isButtonPressed设为true,自然无法切回原状态,需要点击时对状态取反,同时根据状态执行「关注/取关」两套Firestore操作逻辑。
2. 补充取关场景的Firestore操作
取关时需要:
- 当前用户的关注数减1
- 删除目标用户的Followers集合中对应当前用户的文档
- 目标用户的粉丝数减1
优化建议:存储关注关系时直接使用当前用户的uid作为Followers子集合的文档ID,取关时可直接删除无需额外查询,提升性能。
3. 完整修改后的代码示例
业务逻辑部分
bool isButtonPressed = false; // 点击按钮时触发的逻辑 void toggleFollow() async { getCurrentUser(); // 先判断当前状态,执行对应操作 if (!isButtonPressed) { // 执行关注逻辑 await FirebaseFirestore.instance.collection('users').doc(user!.uid).update({ 'following' : FieldValue.increment(1), }); // 这里用当前用户uid作为文档id,方便后续删除 await FirebaseFirestore.instance.collection('users').doc(docId).collection('Followers').doc(user!.uid).set({ 'follower' : username, 'userid' : user!.uid, 'avatar' : profile, }); await FirebaseFirestore.instance.collection('users').doc(docId).update({ 'followers' : FieldValue.increment(1), }); } else { // 执行取关逻辑 await FirebaseFirestore.instance.collection('users').doc(user!.uid).update({ 'following' : FieldValue.increment(-1), }); // 直接用当前用户uid删除对应关注文档 await FirebaseFirestore.instance.collection('users').doc(docId).collection('Followers').doc(user!.uid).delete(); await FirebaseFirestore.instance.collection('users').doc(docId).update({ 'followers' : FieldValue.increment(-1), }); } // 操作成功后再更新UI状态 setState(() { isButtonPressed = !isButtonPressed; }); }
按钮组件部分
ElevatedButton( onPressed: () async => toggleFollow(), style: isButtonPressed ? ElevatedButton.styleFrom( onPrimary: Colors.white24, primary: Colors.white24, ) : ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.blue, ), child: Padding( padding: EdgeInsets.only(left: 50 , right:50 ), child: isButtonPressed ? Text( "Following", style: TextStyle( color: Colors.white, ) ) : Text( "Follow", style: TextStyle( color: Colors.white, ) ) ), ),
额外注意事项
- 建议给Firestore操作加异常捕获,避免网络请求失败时UI状态和后端数据不一致
- 关注/取关的计数和文档操作建议用Firebase事务处理,防止并发操作时数据计数错误
内容的提问来源于stack exchange,提问作者RETRo1o1
相关产品推荐
相关产品推荐

