【问题标题】:Is it possible to read a Text widget's font size that has been set by a FittedBox?是否可以读取由 FittedBox 设置的 Text 小部件的字体大小?
【发布时间】:2021-11-12 17:01:35
【问题描述】:

我希望基于另一个文本小部件的字体大小。如果我将 Text 小部件放入 FittedBox 并填充到容器中,则 Text 小部件的大小相同,但由于字符串长度,字体会有所不同。有没有什么方法可以在 Text 小部件被一个合适的框拉伸或收缩后获取它的字体大小,然后 setState 我需要的所有其他字体大小都相同?我来的最远是这样的:

  double _getFontSize(double w) {
    Container c = Container(child: FittedBox(fit: BoxFit.fill,child: Text('What is my font size?',),), width: w,);
    FittedBox f = c.child as FittedBox;
    Text t = f.child as Text;
    return t.style!.fontSize!;
  } //My thinking was that the FittedBox did it's sizing before drawing but that is not the case.

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    var fontSize = _getFontSize(width);

    return yadayadayada;
  }

假设我有一个看起来像这样的小部件布局:

class _Foo extends State<Bar> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: Column(
                  children: [
                    Text('Short'), //--------------I WANT THIS GUY TO HAVE THE SAME FONT SIZE AS THE GUY BELOW
                  ],
                ),
              ),
              Expanded(child: Column()),
            ],
          ),
        ),
        Expanded(
          child: Row(
            children: [
              Expanded(child: Column()),
              Expanded(
                child: Column(
                  children: [
                    FittedBox(fit: BoxFit.fill,child: Text('Much Longer'),), //I WANT TO GET THIS GUY'S FONT SIZE
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    )
  }
}

【问题讨论】:

  • 你是不是想得到自动适应类型的东西?
  • 在 FittedBox 调整了 Text 小部件的大小后,我试图让所有 Text 小部件的字体大小基于 FittedBox 中的一个 Text 小部件。

标签: flutter dart


【解决方案1】:

我可以给你一些资源来帮助你实现你的用例:
1-auto_size_text 是一个很棒的包,并且具有组文本功能可以解决您的用例
2- code_snippet 测量文本大小
3- measure size 可能会有所帮助
4- LayoutBuilder 也可以帮助你

【讨论】:

  • auto_size_text 包正是我所需要的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 2016-02-05
  • 2011-03-14
  • 1970-01-01
  • 2017-08-30
  • 2019-12-23
相关资源
最近更新 更多