Home > Software design >  flutter_bloc BlocBuilder not rebuilding as well state change not observed in BlocObserver
flutter_bloc BlocBuilder not rebuilding as well state change not observed in BlocObserver

Time:05-26

i am new to flutter , trying to implement counter app using flutter_bloc. widget withBlocBuilder is not rebuilding even after emitting state. added BlocObserver and found only once state change happened . could someone help ? below is the git repo : https://github.com/gopiKrishnaPuligundla/japa_counter

CodePudding user response:

The problem was you were incrementing both the old state and the new state in increment() of your CounterBloc.

void increment(IncrementCounter event, Emitter<CounterState> emit) {
  print("increment");
  // ------------ Here you are updating the old State ---------------
  state.counter.incrementCount();
  // ----------------------------------------------------------------
  emit(
    CounterState(
      counter: Counter(
        liveCount:state.counter.liveCount,
        liveRounds: state.counter.liveRounds,
      )
    )
  );
}

So by the time, the CounterBloc compare the new state with the old one which you defined by the Equatable, it will appear the same.

@override
List<Object?> get props => [
  _liveRounds,
  _liveCount
];

// Old State
// [0, 2]

// New State
// [0, 2]

// They are considered the same, so BlocBuilder will not be updated

How to fix it? Well, you can just create new CounterState with the updated value and not via updating the old one.

void increment(IncrementCounter event, Emitter<CounterState> emit) {
  print("increment");
  // -------------- Do not update the old state ----------------------
  // state.counter.incrementCount();
  // -----------------------------------------------------------------
  emit(
    CounterState(
      counter: Counter(
        // ------------------- Increment on New State-----------------
        liveCount:state.counter.liveCount   1,
        // -----------------------------------------------------------
        liveRounds: state.counter.liveRounds,
      ),
    ),
  );
}

For decrement(),

void decrement(DecrementCounter event, Emitter<CounterState> emit) {
  print("decrement");
  // state.counter.decrementCount();
  emit(
    CounterState(
      counter: Counter(
        liveCount:state.counter.liveCount - 1,
        liveRounds: state.counter.liveRounds,
      ),
    ),
  );
}
  • Related