【问题标题】:How to get the width of the dynamic text widget in flutter?如何在颤动中获取动态文本小部件的宽度?
【发布时间】:2023-04-10 18:15:01
【问题描述】:

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

【问题讨论】:

    标签: flutter text widget


    【解决方案1】:

    您可以在 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
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2019-03-10
      • 2021-05-19
      • 2020-11-02
      • 2020-03-01
      • 2019-09-07
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多