Skip to content

prefer_align_over_container

v0.1.0 Warning Fix Widget Replacement

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

A Container builds up to seven render objects depending on which arguments it got. With only alignment set, exactly one of them does anything, and that one is Align. Naming it directly says what the widget is for. The quick fix is a rename — Container becomes Align and the arguments stay put.

See also: Align | Container

// A badge pinned to the corner of a card.
Container(
alignment: Alignment.topRight,
child: const Icon(Icons.star),
);
Align(
alignment: Alignment.topRight,
child: const Icon(Icons.star),
);

Align expands to fill its parent and places the child within it, exactly as the Container did:

// Don't
SizedBox(
height: 120,
child: Container(
alignment: Alignment.bottomCenter,
child: const Text('Caption'),
),
);
// Do
SizedBox(
height: 120,
child: Align(
alignment: Alignment.bottomCenter,
child: const Text('Caption'),
),
);

They exist on both widgets, so a Container carrying them plus alignment is still reported:

// Don't
Container(
key: const ValueKey('badge'),
alignment: Alignment.centerLeft,
child: const Text('New'),
);
// Do
Align(
key: const ValueKey('badge'),
alignment: Alignment.centerLeft,
child: const Text('New'),
);

Rewriting to Align(alignment: Alignment.center, …) is then reported by prefer_center_over_align, which wants Center. Go straight there:

// Don't
Container(alignment: Alignment.center, child: const Text('Hi'));
// Do — skip the intermediate Align
Center(child: const Text('Hi'));

Any other argument silences it. One padding, color, width or decoration and the Container is doing work Align cannot:

// Not reported — the colour has nowhere to go on an Align
Container(
alignment: Alignment.topLeft,
color: const Color(0xFFEEEEEE),
child: const Text('Hello'),
);

Only a direct Container(...) is matched. A factory or helper that returns a Container is not looked through.

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

many_lints.yaml
rules:
prefer_align_over_container: true

To turn it off again:

many_lints.yaml
rules:
prefer_align_over_container: false

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