BeHappy
BeHappy

Reputation: 3988

yielding new state not update UI

I yield same state but with different object in my bloc but BlocBuilder not called again. How I can do this scenario ? My mapEventToState is

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

Upvotes: 1

Views: 186

Answers (3)

Theja reddy
Theja reddy

Reputation: 1

Removing equatbale rebuilds every time even values of the properties are not changed. Instead create new state instance every time.

Upvotes: 0

BeHappy
BeHappy

Reputation: 3988

Removing Equatable solve the problem.

Upvotes: 0

Federick Jonathan
Federick Jonathan

Reputation: 2864

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.

If you want to change the value of the state, make a copyWith function for your model 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);
}

Upvotes: 1

Related Questions