如何在 flutter 中获取动态文本小部件的宽度?

How to get the width of the dynamic text widget in flutter?

我的文本小部件中的文本字体是动态的。字体的宽度和高度根据不同的字体类型而变化。如何获取根据字体变化的文本小部件的宽度或高度值。

您可以在文本小部件中使用 GlobalKey,然后在其他地方检查它的大小

GlobalKey myKey = GlobalKey();
...

Text('MyText, key: myKey)

然后使用 GlobalKey 的 currentContext 检查其大小(在构建后的回调中)

print(myKey?.currentContext?.size);

但在此之前,您需要构建文本小部件

The current context is null if there is no widget in the tree that matches this global key

如果您想知道在创建 TextWidget 之前它将使用的大小,您可以尝试在某处创建一个 TextSpan(例如在 initState 中)

TextSpan longestParagraphTest = TextSpan(
   text: "This is all my Text",
   style: myTextStyle, //define the style it willl use, fontSize, etc.
);
TextPainter _textPainter = TextPainter(text: longestParagraphTest, textDirection: TextDirection.ltr, maxLines: 1)..layout(minWidth: 0.0, maxWidth: double.infinity);
width = _textPainter.width; //This is the width it requires
height = _textPainter.height; //This is the height it requires