Home > Software engineering >  How to calculate size of text string in flutter before rendering it?
How to calculate size of text string in flutter before rendering it?

Time:03-30

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.

CodePudding user response:

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

  • Related