How to dynamically resize text in Flutter

0 votes

I retrieve a piece of text from an API. I want to allot a set amount of space to it (say a max Container with width: 300.0 and height: 100.0). Sometimes, the piece of text fits in this Container with font size 30.0. In other times, it won't fit unless I set the text size to 24.0.

Is there a way to dynamically resize text based on its parent container space?

I've built a Container with a ConstrainedBox, which lets me define the max size of the text space. I've also wrapped my Text with a LayoutBuilder. I was hoping that I could check the height of the space of the text, and based on that, determine how to size the text. Like this:

    Container(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minWidth: 300.0,
          maxWidth: 300.0,
          minHeight: 30.0,
          maxHeight: 100.0,
        ),
        child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
          if (/* height is larger than 100.0? height is over the constraints? */) { return textWithSize24(); }
          return textWithSize30();
        }),
      ),
    ),

How can I determine the "height that the text would take up if it were size 30.0"? Maybe I'm approaching this the wrong way and I'm supposed to use maxLines to determine this instead? But how do we know that we've reached more than maxLines?

The other way to do it is to use the number of characters in my String to determine when to change font sizes. This seems kind of manual.

Mar 27, 2023 in Flutter by Ashwini
• 5,430 points
11,015 views

1 answer to this question.

0 votes

You can use the FittedBox widget to dynamically resize text based on its parent container space in Flutter. This widget scales its child to fit its parent's available space, and you can set a range of font sizes using the minFontSize and maxFontSize properties of the Text widget. Alternatively, you can use the AutoSizeText package, which automatically resizes the text to fit its parent container based on the available space.

To know more, join our Flutter Course today.

answered Mar 27, 2023 by Tej

Related Questions In Flutter

0 votes
1 answer

How to change Android minSdkVersion in Flutter Project?

Yes, you can change the minSdkVersion in ...READ MORE

answered Mar 21, 2023 in Flutter by Tej
15,143 views
0 votes
1 answer

How to implement drop down list in flutter?

You're close! The error you're getting is ...READ MORE

answered Mar 26, 2023 in