In Flutter, I want to insert a widget (an icon) at the end of a text block, but I want to ensure that the widget stays inline with the last word of the text and doesn’t wrap to a new line by itself. If the text is super long, the text should be cut off. Otherwise words can be split.
Text.rich(
TextSpan(
children: [
TextSpan(
text: title,
style: textStyle,
),
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Padding(
padding: const EdgeInsets.only(left: 6.0),
child: icon,
),
),
],
),
)
I’ve tried putting the icon in a row with the last character but then it doesn’t move the last word itself onto the next line in some cases.
The first two images are as expected.
The last image here shows what I’m trying to avoid:
3
Answers
Well, I believe it’s not possible to directly achieve this without manipulating the "String" that you want to place next to the icon. This is because spaces between words break once there’s no more space in the line.
However, I came up with a sort of "workaround" that might help. I created two functions to manipulate the provided text:
_onlyLastWords
and_withoutLastWords
. I made it so that if you want to increase or decrease the number of words, you only need to change the value of words.With this, I structured it like this:
The idea is to create an element with the last two words plus the icon, so that when there’s no space, there are always at least two words before the icon.
A simpler way would be to use Unicode like this –new Text(‘2018 u00a9 Author’s Name’),
You can extract the last word and place it in the
Row
with the icon inside theWidgetSpan
. In the code below, I have place the wordhello
with the icon ABC inside theRow
and placed theRow
inside theWidgetSpan
.