flutter_bloc BlocBuilder 未重建以及未在 BlocObserver 中观察到状态变化

flutter_bloc BlocBuilder not rebuilding as well state change not observed in BlocObserver

我是 flutter 的新手,正在尝试使用 flutter_bloc 实现计数器应用程序。 即使在发出状态后,widget withBlocBuilder 也不会重建。 添加了 BlocObserver 并仅在发生状态更改时发现。 有人可以帮忙吗? 下面是 git 回购: https://github.com/gopiKrishnaPuligundla/japa_counter

问题是您在 CounterBlocincrement() 中增加旧状态和新状态。

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,
      )
    )
  );
}

所以到时候,CounterBloc 将新状态与您通过 Equatable 定义的旧状态进行比较,它们看起来是一样的。

@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

如何解决?好吧,您可以只使用更新后的值创建新的 CounterState,而不是通过更新旧值。

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,
      ),
    ),
  );
}

对于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,
      ),
    ),
  );
}