Im trying to use the flutter_bloc v8 for a counter app but I can't access the value of the state to update it. Its telling me state is undefined. I know we can simplify it by using Cubit but I want to see how it'll work with normal bloc.
counter_state.dart
abstract class CounterState {}
class CounterValue extends CounterState {
int value;
CounterValue(this.value);
}
class CounterLoading extends CounterState {}
counter_bloc.dart
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterValue(0)) {
on<IncrementEvent>((event, emit) => _increment(emit));
on<DecrementEvent>((event, emit) => _decrement(emit));
}
}
void _increment(Emitter<CounterState> emit) {
emit(CounterValue(state.value 1));
}
void _decrement(Emitter<CounterState> emit) {
emit(CounterValue(state.value 1));
}
CodePudding user response:
the state is unreachable because you have defined your functions outside of CounterBloc.
try this:
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterValue(0)) {
on<IncrementEvent>((event, emit) => _increment(emit));
on<DecrementEvent>((event, emit) => _decrement(emit));
}
void _increment(Emitter<CounterState> emit) {
emit(CounterValue(state.value 1));
}
void _decrement(Emitter<CounterState> emit) {
emit(CounterValue(state.value 1));
}
}