How can I get the size of the Text Widget in flutter

前端 未结 5 704
不思量自难忘°
不思量自难忘° 2020-11-29 01:19

I\'ve painted a shape for the background of my content of Text.

I want the background autoscale the Text, even the softWrap being true.

5条回答
  •  有刺的猬
    2020-11-29 01:44

    Problem with other answers is that if you use Text widget to display your text and constraint it with measurements result without considering default font family and scale factor, then you will get wrong results because Text widget is using device's textScaleFactor by default and passing it to RichText widget inside of it. This is the correct code to measure text size:

    final Size size = (TextPainter(
            text: TextSpan(text: text, style: textStyle),
            maxLines: 1,
            textScaleFactor: MediaQuery.of(context).textScaleFactor,
            textDirection: TextDirection.ltr)
          ..layout())
        .size;
    

提交回复
热议问题