컨텐츠로 건너뛰기

Avoid Public Bloc Methods

이 콘텐츠는 아직 해당 언어로 제공되지 않습니다.

newdartrecommended

Avoid exposing public methods on Bloc instances.

Blocs react to incoming events and emit outgoing states. As a result, the recommended way of communicating with a bloc instance is via the add method. In most cases, there’s no need to create additional abstractions on top of the add API.

Bloc Architecture

DO NOT expose public methods on bloc instances.

BAD:

counter_bloc.dart
import 'package:bloc/bloc.dart';
enum CounterEvent { increment };
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterEvent>((event, emit) => emit(state + 1));
}
// Avoid public bloc methods!
// Prefer to use [add] directly.
void increment() => add(CounterEvent.increment);
}

GOOD:

counter_bloc.dart
import 'package:bloc/bloc.dart';
enum CounterEvent { increment };
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<CounterEvent>((event, emit) => emit(state + 1));
}
}

To enable the avoid_public_bloc_methods rule, add it to your analysis_options.yaml under bloc > rules:

analysis_options.yaml
bloc:
rules:
- avoid_public_bloc_methods