Reputation: 620
I have a TextSpan (see code below). I want to calculate the width of the text so I can align my text in the center.
How do I do that ?
final textSpan = TextSpan(
text: ' $title ',
style: TextStyle(
color: titleColor,
fontSize: fontSize,
height: 1.0,
backgroundColor: backgroundColor,
),
);
Upvotes: 1
Views: 1312
Reputation: 3136
To calculate size of any text you can use this function:
Size measure(String text, TextStyle style,
{int maxLines: 1, TextDirection direction = TextDirection.ltr, double maxWidth = double.infinity}) {
final TextPainter textPainter =
TextPainter(text: TextSpan(text: text, style: style), maxLines: maxLines, textDirection: direction)
..layout(minWidth: 0, maxWidth: maxWidth);
return textPainter.size;
}
as you can see - you have to pass text and textsyle, optionally maxlines, text direction and width constraint.
Upvotes: 1
Reputation: 166
final textSpan = TextSpan(
text: ' $title ',
style: TextStyle(
color: titleColor,
fontSize: fontSize,
height: 1.0,
backgroundColor: backgroundColor,
),
);
final TextPainter textPainter = TextPainter(
text: textSpan)
..layout(minWidth: 0, maxWidth: double.infinity);
print(textPainter.size); //the TextSpan width
Upvotes: 1