Home > Software design >  Adapt card height to fontSize in flutter
Adapt card height to fontSize in flutter

Time:10-08

I have a card with 2 Text widgets and I want to have them not overflowing regardless of the fontSize set in accessibility settings by the user. I'm doing this calculus and it overflows right away. I added a constant to the total height so it doesn't overflow but when I increased the font size even more from settings it's overflowing again.

What am I missing here?

double getCardHeight(BuildContext context) {
final scale = MediaQuery.of(context).textScaleFactor;

double bodyFontSize = Theme.of(context).textTheme.bodyText2?.fontSize ?? 0;
double bodyLineHeight = bodyFontSize * scale;

double titleFontSize = Theme.of(context).textTheme.headline5?.fontSize ?? 0;
double titleLineHeight = titleFontSize * scale;

final textsHeight =
    (titleLineHeight * titleMaxLines)   (bodyLineHeight * bodyMaxLines);
final cardHeight = textsHeight   verticalPadding * 2;
print("card height = $cardHeight");

return cardHeight;}

CodePudding user response:

I am wondering why you need to calculate this, as cards normally set their own height to fit all the content inside. If you could post the code containing you cards, we can help you better.

Also, you might want to use a debugger to see where the function does not behave as you want.

CodePudding user response:

You should do this a bit differently. Instead of calculating the text height and then using that to size the cards, put your text widgets inside Flexible widgets and put those flexible widgets inside a Row.

Row(
                  children: [
                    Flexible(
                      child: Text('My text'),
                    )
                  ],
                ),

This will make it so the text wraps whenever its about to overflow.

CodePudding user response:

I figured it out. I have my text styles defined in the theme. However, I did not set a height to the styles. When doing the math I assumed the height of the font is 1 but it was not. After I specified height: 1 to all my text styles the math works fine

  • Related