Flutter Bloc使用Equatable时新增数据后无法触发相同状态发射
Flutter Bloc中Equatable状态重复发射失效问题
我在Flutter Bloc中使用Equatable,尝试发射包含不同数据集的相同状态,但当列表新增5条记录时,状态无法完成第二次发射。
状态发射代码
loadedState = LoadedPosts( now: DateTime.now(), post: List.from(postDetailsFilteredPostResponse, growable: false), newCount: 0, friends: List.from(postFriendsResponse, growable: false), likes: List.from(postLikesResponse, growable: false), comments: List.from(postCommentsResponse, growable: false), photos: List.from(postPhotosResponse, growable: false), userDetail: userDetail); emit(loadedState);
状态类定义
abstract class PostState extends Equatable{ @override List<Object?> get props => []; } class LoadedPosts extends PostState{ List<Post> post = List<Post>.filled(5, Post(postId: '')); final List<User>? friends; final List<Images> photos; final List<UserLikes> likes; final List<UserComments> comments; final User? userDetail; final int newCount; final DateTime now; LoadedPosts({ required this.post, required this.friends, required this.photos, required this.likes, required this.comments, required this.newCount, required this.now, this.userDetail }); @override List<Object?> get props => [now, post]; }
问题原因与解决方案
问题核心是Post类未继承Equatable,导致LoadedPosts中post列表的对比基于引用相等而非内容相等。即便列表新增记录,Equatable仍会判定两次的post列表相等;若两次发射的now时间差极小(如同步操作),会被识别为同一状态,Bloc便会跳过此次发射。
解决步骤:
- 让
Post类继承Equatable,并重写props方法,将所有需要参与对比的字段加入props:
class Post extends Equatable { final String postId; // 补充Post类的其他字段 const Post({required this.postId}); @override List<Object?> get props => [postId]; // 包含所有需对比字段,确保内容变化能被识别 }
- (可选)若
User、Images等关联类也会在状态中发生变化,同样需要让它们继承Equatable并实现props,保证状态对比的准确性。
修改完成后,当post列表内容变化时,Equatable能正确识别状态差异,Bloc即可正常发射新状态。
内容的提问来源于stack exchange,提问作者nidhi patnaik
相关产品推荐
相关产品推荐

