Zum Inhalt springen

Avoid Public Fields

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

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