flutter

while using bloc arithmatic operator not working in flutter?


class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(CounterState()) {
    on<CounterIncrementEvent>((event, emit) {

      emit(state.copyWith(count: state.count++));
// if i use state.count+1 its working.

    });
    on<CounterDecrementEvent>((event, emit) {
      emit(state.copyWith(count: state.count--));
// if i use state.count-1 its working.
    });
  }
}

while using __ or ++ its not working and when i changed state.count+1 or state.count-1 its working find..then whats the issue..


Solution

  • When you use state.count++ or state.count--, the value passed to emit is the original value of state.count (before the increment or decrement). After that, the value of state.count is updated, but this updated value is not used in the emit call. This means the state is not being updated as you expect.

    When you use state.count + 1 or state.count - 1, you are directly passing the updated value to emit

    If you make the count variable not final, your code with state.count++ and state.count-- will work, but this is not a recommended approach in most cases.