prefer_bloc_extensions
v0.4.0 Warning Fix Bloc / Riverpod
This rule flags usage of BlocProvider.of() and RepositoryProvider.of() and suggests using the shorter context.read() or context.watch() extensions instead. When listen: true is passed, the rule suggests context.watch().
Why use this rule
Section titled “Why use this rule”The context.read() and context.watch() extensions are shorter, more readable, and make the intent clearer. With BlocProvider.of(), developers can easily forget the listen parameter or misconfigure it. The extension methods make the distinction between one-time reads and reactive watches explicit in the method name itself.
See also: BlocProvider | context.read vs context.watch
import 'package:flutter/widgets.dart';import 'package:flutter_bloc/flutter_bloc.dart';
abstract class CounterEvent {}
class CounterBloc extends Bloc<CounterEvent, int> { CounterBloc() : super(0);}
class CounterCubit extends Cubit<int> { CounterCubit() : super(0);}
class MyRepository {}
void examples(BuildContext context) { final bloc = BlocProvider.of<CounterBloc>(context); final watched = BlocProvider.of<CounterCubit>(context, listen: true); final repo = RepositoryProvider.of<MyRepository>(context);}import 'package:flutter/widgets.dart';import 'package:flutter_bloc/flutter_bloc.dart';
abstract class CounterEvent {}
class CounterBloc extends Bloc<CounterEvent, int> { CounterBloc() : super(0);}
class CounterCubit extends Cubit<int> { CounterCubit() : super(0);}
class MyRepository {}
void examples(BuildContext context) { final bloc = context.read<CounterBloc>(); final cubit = context.watch<CounterCubit>(); final repo = context.read<MyRepository>();}Configuration
Section titled “Configuration”This rule is in the opinionated preset, so it is on with
preset: opinionated, or by name:
rules: prefer_bloc_extensions: trueTo turn it off again:
rules: prefer_bloc_extensions: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_bloc_public_methods— Prevent public methods, getters, and setters in Bloc classes.avoid_passing_bloc_to_bloc— Prevent Bloc/Cubit classes from depending on other Bloc/Cubit instances.avoid_duplicate_bloc_event_handlers— Register each bloc event type exactly once.emit_new_bloc_state_instances— Emit a new state instance instead of the existing state object.