Skip to content

Avoid BuildContext Extensions

newdart

Avoid using BuildContext extensions to access Bloc or Cubit instances.

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>(...) |

Avoid using BuildContext extensions to interact with Bloc or Cubit instances.

BAD:

counter_page.dart
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:

counter_page.dart
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'),
),
],
);
}
}

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

analysis_options.yaml
bloc:
rules:
- avoid_build_context_extensions
Morty Proxy This is a proxified and sanitized view of the page, visit original site.