Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate size of text string in flutter before rendering it?

If I have the text size and font, then how can I calculate the width and height of the String before It is rendered on the screen? I need to know because I want to put it inside a Container of the appropriate size before drawing it on the screen.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use TextPainter to layout the text and get its width and height.

For example:

final textSpan = TextSpan(
  text: 'Do you wanna build a snowman?',
  style: TextStyle(fontSize: 30, color: Colors.white),
);
final tp = TextPainter(text: textSpan, textDirection: TextDirection.ltr);
tp.layout();
print('text width: ${tp.width}');

Console output:

flutter: text width: 460.0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading