【发布时间】:2023-04-10 18:15:01
【问题描述】:
【问题讨论】:
【问题讨论】:
您可以在 Text Widget 中使用 GlobalKey,然后在其他地方检查其大小
GlobalKey myKey = GlobalKey();
...
Text('MyText, key: myKey)
然后使用 GlobalKey 的 currentContext 来检查它的大小(在它被构建后的回调中)
print(myKey?.currentContext?.size);
但在此之前,您需要构建文本小部件
如果树中没有小部件,则当前上下文为空 匹配这个全局键
如果您想在创建 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
【讨论】: