10

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.

2 Answers 2

18

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

Sign up to request clarification or add additional context in comments.

5 Comments

just for clarification, is the text direction necessary for the function to work properly? I don't know what is the language until runtime
Yes it is. The language should be based on the string you pass in, isn't it?
@HHH If you need to, you can get the text direction from device: stackoverflow.com/a/61660786/1032613
I support multiple languages for input, I will see how to solve it
@WSBT maybe you can help in this related question here
3

That's a great solution, thankyou, I would just expand it a little to include the TextScale a user can apply from the app settings though.

// create a nice span
final textSpan = TextSpan(
  text: text,
  style: style,
);
// and get the media query
final media = MediaQuery.of(context);
// which we paint with the media's scaling in place please
final tp = TextPainter(
    text: textSpan,
    textDirection: TextDirection.ltr,
    textScaler: media.textScaler);
tp.layout();
// and return the size of the text span we just drew
return tp.size;

1 Comment

great idea to add the scaler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.