Is it possible to force Text widget to use two line space?

Viewed 2014

I need to find out a method to force Flutter Text widget to use two text lines space even if the line is only one. For example in the below photo one card is lower than the other one due to the fact that Text widget use only one line space.

enter image description here

Does anyone know some trick to force Text widget to use maxLines space even if only one line is needed?

5 Answers

Adding minLines to Text is currently an open feature request. You can track it here

For now, a suggested workaround is to use:

str = 'example'; 

Text(
  str + '\n',
  maxLines: 2,
)

you can use \n to set minimum lines (it is a trick)

this issue is still open Github: Add minLines to Text (flutter issue)

          Text(
            '${product.name}\n\n', //equal minlines: 3
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
            style:
                const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),

You could simply use height property in TextStyle:

Text(
  "Some lines of text",
  style: TextStyle(
    fontSize: 14.0,
    height: 1.5 //set height as you want
  )
)

another option would be to use Spacer():

Row(
  children: <Widget>[
    Text('Begin'),
    Spacer(), // Defaults to a flex of one.
    Text('Middle'),
    // Gives twice the space between Middle and End than Begin and Middle.
    Spacer(flex: 2),
    Text('End'),
  ],
)

you can find more details about Spacer in the official docs here

Try this, it will work.

Row(
     children: [
         Expanded(
           flex: 1,
           child: Text(
              'Your long text goes here, you can add as much as you want',
              maxLines: 2,   /// you can change it on your requirements, or may be ignore it
              ),
      )
    ],
)

Here is the best solution I found.

You can set all text styles in one place and get it like so

static TextStyle subtitle2(Color color) =>
  initStyle(color, 14.0, FontWeight.w600);

static TextStyle initStyle(
 Color color, 
 double fontSize, 
 FontWeight fontWeight) =>
  TextStyle(
      height: 1.2,
      fontSize: fontSize,
      color: color,
      fontWeight: fontWeight,
      fontFamily: 'OpenSans');

Don't forget to set height property of Text Style

Then you can define your text like this

TextStyle textStyle = AppTextStyle.headline6(AppColors.onBackground);
int lines = 3;
...
Container(
      height: textStyle.height! * textStyle.fontSize! * lines,
      child: Text('Title', style: textStyle))

For me work Perfectly

enter image description here

Related