How can I get width
and height
of a Text
?
Text(
"吃葡萄不吐葡萄皮",
style: TextStyle(
color: Colors.red,
fontSize: 18
),
),
You can get the size of text if you use a TextPainter
or Paragraph
object. Here is how you would do it with TextPainter
:
final text = '不吃葡萄倒吐葡萄皮';
final style = TextStyle(fontSize: 30);
TextPainter textPainter = TextPainter()
..text = TextSpan(text: text, style: style)
..textDirection = TextDirection.ltr
..layout(minWidth: 0, maxWidth: double.infinity);
print(textPainter.size); // Size(270.0, 43.0)
Actually Text
is widget and get height and width of any widget in flutter you have to use GlobalKey
and assign it to our Widget.
GlobalKey txtKey = GlobalKey();
and set this key to Text
widget
Text(
key: txtKey,
"吃葡萄不吐葡萄皮",
style: TextStyle(
color: Colors.red,
fontSize: 18
),
),
And you can access height/width by write below code else where may be in button press event!
final keyContext = txtKey.currentContext;
if (keyContext != null) {
final txtBox = keyContext.findRenderObject() as RenderBox;
print('height ${txtBox.size.height} and width ${txtBox.size.width}');
}
Here txtBox
return exact size of your text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With