Goal is to center first widget and put to left second widget. However, if centered widget is too long, it should wrap, not overlap on left widget. That’s why Stack is not working.
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(38.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Center me"),
Text("I am left"),
],
),
Row(
children: [
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text("Not very centered")]
),
),
Text("I am left"),
],
),
Stack(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text("Center me, I should wrap because I am too loooooooooooooong ")],
),
Positioned(
right: 0,
child: Text("I am left"),
),
],
)
],
),
),
);
I think it’s a very basic common used UI, it would be nice to have some sort of MainAxisAligment.centerAndLeft
or some Flexible
extension for this.
(The trick that I am currently using to make this work is to have left widget in a variable and put it on both side, then use spaceBetween
, and make Opacity to zero for the right one, but it is an overkill, and reduce available space if the left widget is too long)
2
Answers
Cache your text widget into a local variable:
And put the text variable to build method and wrap with visibility widget below:
The complete code:
Result:
So Adan kinda did what you want but I think you wanted something like if text is too long it should go to the left side. So I added some stuff to Adan’s code. Let me explain what I did.
I added centerText to an element because I assume that the information will come from backend. I added a LayoutBuilder widget to the Expanded so that I can get the box’s constraints. In the initState method, I called
checkOverflow
after rendering done. That code will create a TextSpan with TextPainter so normally how much space as width that Text element will get. After that if it does, it will set the state and the Visible element will be gone, your text will still centered but that will take much more space. If the text exceeeds that too, then it will became ‘…’This is the full code:
These are the examples:
Short Text
Long Text No Overflow
Long Text With Overflow
I hope this is what you wanted. Happy coding!!!