flutter - 如何在颤动中获取动态文本小部件的宽度?
解决方案
您可以在文本小部件中使用 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
推荐阅读
- java - Spring FileSystemResource 在保留原始文件名的同时下载文件
- javascript - 动态附加元素后重新应用样式属性
- javascript - 未捕获的类型错误:XXX.then 不是函数
- php - 试图从 symfony3 中的全局命名空间加载类“Imagick”
- xamarin - xamarin UITest - 推送通知阻止自动化
- ruby-on-rails - 如何测量反应时间?
- c++ - 传递带有 const 内容的向量
- c# - 使用 c# 将 Excel 导入到 Access
- powershell - 如何在PowerShell中替换前面有零个、一个或多个空格的字符串
- java - 如何使用 okhttp 在服务器上发送我的重新编码文件