avoid-duplicate-bloc-event-handlers
Warns when a bloc declares multiple event handlers for the same event.
Adding multiple handlers is usually a mistake and should not happen. Try changing the event name or creating a single method that combines multiple handlers.
⚙️ Config
Set additional-methods
(default is empty) to add additional methods used for listening to bloc events.
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-duplicate-bloc-event-handlers:
additional-methods:
- customOn
Example
❌ Bad:
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterIncrementEvent>(_handle);
this.on<CounterIncrementEvent>(_handleCorrect); // LINT: Avoid multiple handlers for the same bloc event. Try refactoring this handler to only have one.
on<CounterIncrementEvent>(_handleSync); // LINT: Avoid multiple handlers for the same bloc event. Try refactoring this handler to only have one.
on<CounterDecrementEvent>((event, emit) => emit(state - 1));
// LINT: Avoid multiple handlers for the same bloc event. Try refactoring this handler to only have one.
on<CounterDecrementEvent>((event, emit) async {
emit(state + 1);
await Future.delayed(const Duration(seconds: 3));
add(CounterDecrementEvent());
});
}
}
✅ Good:
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterIncrementEvent>(_handlerWithAllLogic);
on<CounterDecrementEvent>(_handle);
}
}