prefer-container
Suggests replacing a sequence of widgets with a single Container
widget.
The Container
widget uses various widgets under the hood (e.g. Align
, Padding
, ClipPath
, etc.), and if a widget tree has a matching sequence, such sequence can be replaced with the Container
widget, which helps to reduce the overall nesting level.
⚙️ Config
Set min-sequence
(default is 3
) to configure the minimum number of widgets after which the Container widget should be suggested.
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-container:
min-sequence: 3
Example
❌ Bad:
// LINT: This sequence of widgets (Align > Padding > Transform) can be replaced with a single Container widget.
Align(
alignment: Alignment.center,
child: Padding(
padding: EdgeInsetsGeometry.right,
child: Transform(
transform: Matrix4(),
child: Padding(padding: EdgeInsetsGeometry.right),
),
),
);
✅ Good:
Container(
padding: EdgeInsetsGeometry.right,
alignment: Alignment.center,
transform: Matrix4(),
child: Padding(padding: EdgeInsetsGeometry.right),
);
// Correct, differs from what the Container creates
Align(
child: Padding(
padding: EdgeInsetsGeometry.right,
child: Transform(
transform: Matrix4(),
transformHitTests: false,
child: Padding(padding: EdgeInsetsGeometry.right),
),
),
);