How to dynamically resize text in Flutter? #45122
-
|
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: 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. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
|
Simply just wrap your Text widget to FittedBox widget like, Here I want to resize my AppBar text based on width. |
Beta Was this translation helpful? Give feedback.
-
|
Works like a charm, awesome solution. |
Beta Was this translation helpful? Give feedback.
-
|
I find my text is forced to fill the box. Is there a way of constraining a max font size with this method? |
Beta Was this translation helpful? Give feedback.
-
|
@briltec I faced the same issue, use github.com/leisim/auto_size_text instead. More flexible |
Beta Was this translation helpful? Give feedback.
Simply just wrap your Text widget to FittedBox widget like, Here I want to resize my AppBar text based on width.
AppBar( centerTitle: true, title: FittedBox( fit: BoxFit.fitWidth, child: Text('Hey this is my long text appbar title') ), ),Text will be resized based on width of AppBar.