Skip to content

use_closest_build_context

v0.4.0 Warning Widget Best Practices

This rule catches cases where an outer BuildContext is used inside a nested builder callback (Builder, LayoutBuilder, etc.) that provides its own context. This commonly happens when the inner parameter is renamed to _ because it was previously unused, and then the outer context is accidentally referenced.

Using the wrong BuildContext can cause lookups like Theme.of(context) or Navigator.of(context) to find the wrong ancestor widget. For example, inside a Builder the outer context does not reflect widgets introduced by the Builder itself. This leads to subtle bugs where your theme, navigator, or scaffold operations target the wrong part of the widget tree.

See also: BuildContext

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Builder(
builder: (_) {
// Uses the outer context instead of the Builder's own context
return _buildChild(context);
},
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Builder(
builder: (context) {
// Uses the Builder's own context
return _buildChild(context);
},
);
}
}

To disable this rule:

plugins:
many_lints:
diagnostics:
use_closest_build_context: false