Reputation: 1812
I have a Row
filling a Container
which may have between one and three fixed-sized children. I'm using MainAxisAlignment.spaceBetween
, and when there's more than one child, it works as expected: with two children, they end up at the edges, and if there are three, two end up at the edges and one in the center.
Container(
width: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(width: 30, height: 20),
SizedBox(width: 30, height: 20),
SizedBox(width: 30, height: 20),
],
),
);
However, when there's only one child, it's placed at the start of the Row
, and I'd like to have it at the center. I can certainly achieve what I need by checking the number of children beforehand and changing the MainAxisAlignment
to center
, but I was wondering if there's a more elegant way to combine spaceBetween
and center
.
Upvotes: 2
Views: 1117
Reputation: 7109
You can use MainAxisAlignment.spaceEvenly
(or spaceAround
) to center the single child. To make the two children float left and right (because in spaceEvenly
there will be extra spaces in left and right), you can add Spacer
to the children of the Row
(works with any number of children).
Code:
List<Widget> rowChildren = [
SizedBox(width: 30, height: 20, child: Container(color: Colors.red)),
SizedBox(width: 30, height: 20, child: Container(color: Colors.yellow)),
SizedBox(width: 30, height: 20, child: Container(color: Colors.green)),
];
@override
void initState() {
super.initState();
int l = rowChildren.length;
for (int i = 1; i < 2 * l - 1; i += 2) {
rowChildren.insert(i, Spacer()); // adding Spacer between the two children
}
}
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: rowChildren
),
Result (a single child):
Result (two children):
Result (three children):
Upvotes: 0
Reputation: 334
add crossAxisAlignment: CrossAxisAlignment.center,
property to Raw Widget:
the code :
Container(
width: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(width: 30, height: 20),
SizedBox(width: 30, height: 20),
SizedBox(width: 30, height: 20),
],
),
);
Upvotes: 1