0

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:

String withExtraNextLineCharacters(String text, int count) {
  String nextLineCharacters = "";
  for (int index = 0; index < (count - 1); index++) {
    nextLineCharacters += "\n";
  }
  return text + nextLineCharacters;
}
rupinderjeet
  • 2,984
  • 30
  • 54
  • Try with Wrap and flexible widget. – Nehil Koshiya Jan 19 '22 at 07:15
  • @NehilKoshiya How can I specify line-count with Wrap or Flexible widget? If you have a working snippet of code, can you please add it as an answer? – rupinderjeet Jan 19 '22 at 07:20
  • 1
    https://stackoverflow.com/questions/52659759/how-can-i-get-the-size-of-the-text-widget-in-flutter just pass text like `'\n'` into `_textSize` function – Nagual Jan 19 '22 at 07:32
  • @Nagual Yes, appending text with `maxLines - 1` count of `\n` characters helps when `maxLines` is defined. Maybe you can add relevant part as an answer. – rupinderjeet Jan 19 '22 at 07:44

1 Answers1

2
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 :-)

Maurice Raguse
  • 4,437
  • 2
  • 29
  • 46