How to create a Text widget with exactly two lines of text in flutter?
I want to create a Text
widget with exactly two lines of text even if text's length is too small or too large.
I can limit upper-bound of line count with maxLines
like below:
Text(subtitle,
maxLines: 2,
style: Theme.of(context).textTheme.bodyText1?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w400,
)
)
I saw some answers where it is suggested to use a SizedBox
to fix the height of content. I didn't feel right to hardcode this value.
I am looking for something like lines
in Android's TextView
. What else can I do to achieve this in Flutter?
Update:
From the help of comments & answers below, I am using following code now:
static String enforceLineCount(String text, int lines) {
String nextLineCharacters = "";
for (int index = 0; index < (lines - 1); index++) {
nextLineCharacters += "\n";
}
return text + nextLineCharacters;
}
Text(subtitle+'\n',
maxLines: 2,
style: Theme.of(context).textTheme.bodyText1?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w400,
)
)
the line break \n
is a placeholder for 2 lines. The subtitle
shift them down... and the maxLines
condition is cutting them away :-)