Skip to content

prefer_center_over_align

v0.1.0 Warning Fix Widget Replacement

Flags Align widgets that use Alignment.center (or omit the alignment parameter, which defaults to center). In these cases, the Center widget is a clearer and more idiomatic replacement.

Center is an Align — a subclass that hard-codes Alignment.center. Using it drops an argument and makes the intent readable at a glance in a deep tree. The quick fix renames the widget and deletes the redundant alignment:.

See also: Center | Align

// A loading spinner in the middle of the page.
Align(
alignment: Alignment.center,
child: const CircularProgressIndicator(),
);
Center(child: const CircularProgressIndicator());

Align’s alignment defaults to Alignment.center, so omitting it is the same widget written less clearly. It is reported too:

// Don't
Align(child: const Text('Centred'));
// Do
Center(child: const Text('Centred'));

Alignment(0, 0) is the centre, so a literal spelled that way is reported as well:

// Don't
Align(alignment: const Alignment(0, 0), child: const Text('Centred'));
// Do
Center(child: const Text('Centred'));

Only exact zeros count — Alignment(0.0, 0.1) is not centre and is not reported.

// Not reported
Align(alignment: Alignment.bottomRight, child: const Text('Corner'));

widthFactor and heightFactor are carried, not dropped. Center declares both, so an Align using them still converts cleanly:

// Don't
Align(
alignment: Alignment.center,
widthFactor: 2,
child: const Text('Wide'),
);
// Do
Center(widthFactor: 2, child: const Text('Wide'));

Only a literal is recognised. An alignment behind a variable or a getter is opaque to the rule, even when it holds the centre:

// Not reported
const spot = Alignment.center;
Align(alignment: spot, child: const Text('Centred'));

Any X.center is matched, not just Alignment.center. AlignmentDirectional.center is the same point, so it converts cleanly — but so would a center constant on some unrelated class of your own, which would not. That shape is rare enough that the rule does not guard against it; if you hit it, silence the line with // ignore: many_lints/prefer_center_over_align.

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

many_lints.yaml
rules:
prefer_center_over_align: true

To turn it off again:

many_lints.yaml
rules:
prefer_center_over_align: false

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