跳转到内容

Avoid Public Fields

此内容尚不支持你的语言。

newdartrecommended

Avoid exposing public fields on Bloc and Cubit instances.

Business logic components maintain their own state and emit state changes via the emit API. As a result, all public facing state should be expose via the state object.

DO NOT expose public fields on bloc and cubit 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 fields!
// Prefer to keep all external state in the [state] object.
int count = 0;
}

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_fields rule, add it to your analysis_options.yaml under bloc > rules:

analysis_options.yaml
bloc:
rules:
- avoid_public_fields