Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get width and height of Text?

Tags:

flutter

dart

How can I get width and height of a Text?

Text(
   "吃葡萄不吐葡萄皮",
   style: TextStyle(
      color: Colors.red,
      fontSize: 18
   ),
),
like image 839
weiKnowi Avatar asked Jun 29 '19 02:06

weiKnowi


2 Answers

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)
like image 175
Suragch Avatar answered Sep 25 '22 15:09

Suragch


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.

like image 38
iPatel Avatar answered Sep 23 '22 15:09

iPatel