Skip to main content

avoid-passing-build-context-to-blocs

added in: 1.24.0
Free+

Warns when a Bloc event or a Cubit method accept BuildContext.

Passing BuildContext creates unnecessary coupling between Blocs and widgets and should be avoided. Additionally, depending on BuildContext can introduce tricky bugs when context is not mounted.

Example

❌ Bad:

bloc.add(CounterEvent(context)); // LINT: Avoid passing 'BuildContext' to blocs.

final event = CounterEvent(context);
bloc.add(event); // LINT: Avoid passing 'BuildContext' to blocs.

...

class CounterCubit extends Cubit<int> {
// LINT: Avoid declaring 'BuildContext' parameters for Cubits.
void another(BuildContext context) async {
...
}
}

✅ Good:

bloc.add(CounterEvent());

class CounterCubit extends Cubit<int> {
void another() async {
...
}
}