How to center middle element in a row of 3 elements (where every element has different length), I want side elements to be maximally on the left/right side and middle element to be exactly on middle?
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
child: Text(
'el',
style: TextStyle(
fontSize: 16,
color: Color(0xFFD50000),
),
),
)),
Expanded(
child: Container(
child: Text('elem',
style: TextStyle(
color: Colors.black,
fontSize: 16,
)),
)),
Expanded(
child: Container(
child: Text('longest elem',
style: TextStyle(
fontSize: 16,
color: Color(0xFFD50000),
)),
)),
],
)
2
Answers
While you are using
Expanded
everyone is getting flex:1. Now you can usealign
from Container and thentextAlign
to make it center(just one of them is needed).Children in your row are properly centered because your expanded takes as much space as possible for every widget on the row’s main axis (horizontally). The proportion is decided by the
Expanded.flex
property which defaults to 1 and thus in your case gives every child same amount of space.Your Text widget isn’t aligning the text in the center. To fix this, provide argument
TextAlign.center
to the parametertextAlign
in yourText
widgets.Refer Flutter’s API Documentation for
Text.textAlign
, andText
widget.Resultant UI for the above code:
I recommend reading this article on flutter. It explains a lot about constraints and alignment.