简体   繁体   English

flutter_bloc BlocBuilder 没有重建,也没有在 BlocObserver 中观察到状态变化

[英]flutter_bloc BlocBuilder not rebuilding as well state change not observed in BlocObserver

i am new to flutter , trying to implement counter app using flutter_bloc.我是flutter的新手,尝试使用flutter_bloc实现计数器应用程序。 widget withBlocBuilder is not rebuilding even after emitting state.即使在发出状态后,带有 BlocBuilder 的小部件也不会重建。 added BlocObserver and found only once state change happened .添加了 BlocObserver 并且仅在状态更改发生时才发现。 could someone help ?有人可以帮忙吗? below is the git repo : https://github.com/gopiKrishnaPuligundla/japa_counter下面是 git repo: https ://github.com/gopiKrishnaPuligundla/japa_counter

The problem was you were incrementing both the old state and the new state in increment() of your CounterBloc .问题是您在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,
      )
    )
  );
}

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.因此,当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

How to fix it?如何解决? Well, you can just create new CounterState with the updated value and not via updating the old one.好吧,您可以使用更新的值创建新的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,
      ),
    ),
  );
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM