A workaround that doesn't require setting maxLines
is to place the Text
in a Stack
with another Text
with a (mostly) identical style (except transparent) that has exactly n
lines.
That way, Flutter will paint both, and the size it takes will be whatever text is more lines. As an extra benefit, you can align the display Text too, making it centred it you want (for example)
return Stack(
alignment: Alignment.center,
children: [
Text(
"\n\n\n",
style: Theme.of(context).textTheme.bodyMedium.copyWith(
color: Colors.transparent,
),
),
Text(
"Single Line of Text",
style: Theme.of(context).textTheme.bodyMedium,
),
],
);
I'll do this quite often if I have a bit of UI where the text changes between one of several possible values, and I don't want the container it's wrapped in to change size every time. Works with buttons, chips, paragraphs, whatever. And also works with the user's font scaling and any translations of the text too.