Avoid BuildContext Extensions
Avoid using BuildContext extensions to access Bloc or Cubit instances.
Rationale
Section titled “Rationale”For consistency and for the sake of being explicit, prefer directly using the
underlying methods instead of BuildContext extensions. This is also beneficial
for testing because it is not possible to mock an extension method.
| extension | explicit method |
| ---------------- | ------------------------------------------------------------------- |
| context.read | BlocProvider.of<Bloc>(context, listen: false) |
| context.watch | BlocBuilder<Bloc, State>(...) or BlocProvider.of<Bloc>(context) |
| context.select | BlocSelector<Bloc, State>(...) |
Examples
Section titled “Examples”Avoid using BuildContext extensions to interact with Bloc or Cubit
instances.
BAD:
import 'package:flutter/material.dart';import 'package:flutter_bloc/flutter_bloc.dart';
class CounterPage extends StatelessWidget { const CounterPage({super.key});
@override Widget build(BuildContext context) { final count = context.watch<CounterBloc>().state;
return Column( children: [ Text('Count: $count'), ElevatedButton( onPressed: () { context.read<CounterBloc>().add(CounterIncrement()); }, child: const Text('Increment'), ), ], ); }}GOOD:
import 'package:flutter/material.dart';import 'package:flutter_bloc/flutter_bloc.dart';
class CounterPage extends StatelessWidget { const CounterPage({super.key});
@override Widget build(BuildContext context) { return Column( children: [ BlocBuilder<CounterBloc, int>( builder: (context, state) => Text('Count: $state'), ), ElevatedButton( onPressed: () { BlocProvider.of<CounterBloc>(context).add(CounterIncrement()); }, child: const Text('Increment'), ), ], ); }}Enable
Section titled “Enable”To enable the avoid_build_context_extensions rule, add it to your
analysis_options.yaml under bloc > rules:
bloc: rules: - avoid_build_context_extensionsbloc: rules: avoid_build_context_extensions: true