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
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
5 Comments
HHH
just for clarification, is the text direction necessary for the function to work properly? I don't know what is the language until runtime
WSBT
Yes it is. The language should be based on the string you pass in, isn't it?
WSBT
@HHH If you need to, you can get the text direction from device: stackoverflow.com/a/61660786/1032613
HHH
I support multiple languages for input, I will see how to solve it
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
Fattie
great idea to add the scaler