In a Row
, how can I ensure that the Text
with "Hello" in it is perfectly centered and not a bit to the left when the right most inner Row
widget has more items than the left most inner Row
widget?
Notice in the screenshot that the "Hello" is slight to the left.
I tried using a Stack
but that seems to not work well if the text is longer than the available space as it causes the text to then overlap the side-colored widgets.
I am using the following code:
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
width: 45,
height: 45,
color: Colors.red,
),
],
),
Text(
"Hello",
textAlign: TextAlign.center,
),
Row(
children: [
Container(
width: 45,
height: 45,
color: Colors.purple,
),
Container(
width: 45,
height: 45,
color: Colors.green,
),
],
)
],
),
)
4
Answers
Wrap both the
Row
s and theText
widget, children of the firstRow
widget, with theExpanded
widget and set themainAxisAlignmnet
of the rightRow
toMainAxisAlignment.end
.Output:
If either of the sides will have more widget’s then you can use the
Wrap
widget instead of the innerRow
widgets which will wrap the overflowing items to the next line.Output:
If you don’t have other widget width you can use
stack
widget:If your text is long, I recommend @OMiShah answer and wrap your text with
expanded
widget.try the following, I made it with the
Stack
widget:I wrote a specific code that might suit your case, here is the result first:
basically, the idea of it is to get the width of both rows in corners, then search for the
max
within between them, then set theText()
width to the screen width size, minus that max multiplied by two, this ensures that it will be exactly in the center and not overlapping the widgets:Hope this helps !