产生新状态不更新 UI

yielding new state not update UI

我产生相同的状态,但在我的集团中有不同的对象,但 BlocBuilder 没有再次调用。 我该怎么做这种情况? 我的 mapEventToState 是

if (event is EditUserProfileImageChanged) {
    UserProfile newUserProfile = state.userProfile;
    newUserProfile.avatar = event.imgSrc;
    yield EditUserProfileTotalState(userProfile: newUserProfile);
}

When we yield a state in the private mapEventToState handlers, we are always yielding a new state instead of mutating the state. This is because every time we yield, bloc will compare the state to the nextState and will only trigger a state change (transition) if the two states are not equal. If we just mutate and yield the same instance of state, then state == nextState would evaluate to true and no state change would occur.

如果您想更改状态的值,请为您的模型创建一个 copyWith 函数 class。

class UserProfile extends Equatable {
  final String name;
  final Image avatar;

  const UserProfile({this.name, this.avatar});

  UserProfile copyWith({String name, Image avatar,}) {
    return UserProfile(
      name: name ?? this.name,
      avatar: avatar?? this.avatar,
    );
  }

  @override
  List<Object> get props => [name, avatar];
}
if (event is EditUserProfileImageChanged) {
    var newState = state.userProfile.copyWith(avatar: event.imgSrc);
    yield EditUserProfileTotalState(userProfile: newState);
}

删除 Equatable 解决问题。

即使属性值未更改,每次删除 equatbale 都会重建。而是每次都创建新的状态实例。