HHH
HHH

Reputation: 165

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.

Upvotes: 10

Views: 5529

Answers (2)

Doug
Doug

Reputation: 31

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;

Upvotes: 2

WSBT
WSBT

Reputation: 36323

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

Upvotes: 18

Related Questions