首页 > 解决方案 > 如何在颤动中获取动态文本小部件的宽度?

问题描述

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

在此处输入图像描述

标签: fluttertextwidget

解决方案


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

GlobalKey myKey = GlobalKey();
...

Text('MyText, key: myKey)

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

print(myKey?.currentContext?.size);

但在此之前,您需要构建 Text Widget

如果树中没有与此全局键匹配的小部件,则当前上下文为 null

如果您想在创建 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

推荐阅读