Skip to content

prefer_padding_over_container

v0.1.0 Warning Fix Widget Replacement

Flags Container widgets that only use the padding or margin parameter (plus optional key and child). When Container is used solely for spacing, the Padding widget is a lighter, more descriptive alternative.

Container composes half a dozen widgets internally; when the only argument is padding or margin, Padding does the same job in one render object. The quick fix does the rewrite for you — it renames the constructor and, for a margin, renames the argument too.

See also: Padding | Container

// A Container used purely to inset a label.
Container(padding: EdgeInsets.all(16), child: Text('Hello'));
Padding(padding: EdgeInsets.all(16), child: Text('Hello'));

On a Container with nothing else set, margin and padding render identically — the margin has no decoration or colour to sit outside of. So the fix renames the argument as it swaps the widget:

// Don't
Container(margin: EdgeInsets.all(16), child: Text('Hello'));
// Do
Padding(padding: EdgeInsets.all(16), child: Text('Hello'));

Padding takes an optional child too, so a childless spacer converts the same way:

// Don't
Container(margin: EdgeInsets.symmetric(horizontal: 8));
// Do
Padding(padding: EdgeInsets.symmetric(horizontal: 8));

padding and margin together is not reported. Those two are no longer equivalent once both exist — the fix would have to merge them — so the rule stays quiet:

// Not reported
Container(padding: EdgeInsets.all(8), margin: EdgeInsets.all(8));

Any other argument stops it. width, color, decoration, alignment — one of them and Container is doing something Padding cannot:

// Not reported
Container(padding: EdgeInsets.all(8), width: 100, child: Text('Hello'));

key and child are the two exceptions; they do not count against the rule.

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_padding_over_container: true

To turn it off again:

many_lints.yaml
rules:
prefer_padding_over_container: false

To keep the rule on but skip certain paths, use per-rule exclude.