1

I'm new to the flutter_bloc state management and I have a problem in the bloc class and state class. The operator '+' isn't defined for the type 'CounterState'. Try defining the operator '+'.

I follow Felix Angelov's instructions here in [Proposal] Replace mapEventToState with on in Bloc.

Here's my code

counter_event.dart

part of 'counter_bloc.dart';

@immutable
abstract class CounterEvent extends Equatable {
  const CounterEvent();

  @override
  List<Object?> get props => [];
}

class IncrementEvent extends CounterEvent {}

class DecrementEvent extends CounterEvent {}

counter_state.dart

part of 'counter_bloc.dart';

@immutable
abstract class CounterState extends Equatable {}

class CounterInitial extends CounterState {
  final int counter;

  CounterInitial(this.counter);

  @override
  List<Object?> get props => [counter];
}

counter_bloc.dart

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

part 'counter_event.dart';
part 'counter_state.dart';

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(CounterInitial(0)) {
    on<IncrementEvent>((event, emit) => emit(state + 1)); //The operator '+' isn't defined for the type 'CounterState'.Try defining the operator '+'.
  }
}
Miguel Rosal
  • 119
  • 1
  • 6

1 Answers1

0

on((event, emit) => emit(state + 1)); // here you are trying to emit an integer, you have to emit a type of CounterInitial, because you passed CounterInitial(0) in super

Try on((event, emit) => emit(CounterInitial(state+1)))