6

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.

HHH
  • 124
  • 1
  • 1
  • 10

1 Answers1

10

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

WSBT
  • 33,033
  • 18
  • 128
  • 133
  • just for clarification, is the text direction necessary for the function to work properly? I don't know what is the language until runtime – HHH Mar 29 '22 at 20:46
  • Yes it is. The language should be based on the string you pass in, isn't it? – WSBT Mar 29 '22 at 20:47
  • @HHH If you need to, you can get the text direction from device: https://stackoverflow.com/a/61660786/1032613 – WSBT Mar 29 '22 at 20:49
  • I support multiple languages for input, I will see how to solve it – HHH Mar 29 '22 at 20:49
  • @WSBT maybe you can help in this related question [here](https://stackoverflow.com/questions/73013522/why-is-this-method-that-determines-size-of-text-before-rendering-giving-differen) – HII Jul 18 '22 at 08:48