在Flutter中,如何使用FittedBox来调整行内文本的大小?

18

我有一行,两边各有一个图标,中间是带有图标的文本:

@override
Widget build(BuildContext context) {
  return Row(
    children: [
      Icon(Icons.arrow_back),
      Expanded(child: SizedBox()),
      Icon(Icons.account_box),
      Text("Some Text Here ", maxLines: 1), // ➜ This is the text.
      Expanded(child: SizedBox()),
      Icon(Icons.arrow_forward),
    ],
  );
}

当文本足够长以填满整个空间时,我想使用FittedBox使其变小。所以我尝试了这个:

      FittedBox(child: Text("Some Text Here. More. More. More. More. More. More. More. More. ", maxLines: 1)), 

它不能正常工作(溢出)。 我认为问题在于Row没有告诉FittedBox它可以拥有的最大尺寸。我已经尝试过使用ExpandedIntrinsicWidthUnconstrainedBoxFlexibleAlignFittedBox一起使用,但都无法解决问题。

我该如何解决这个问题?

更新:我写了一篇文章,这篇文章将帮助我解决这个问题:https://medium.com/flutter-community/flutter-the-advanced-layout-rule-even-beginners-must-know-edc9516d1a2

2个回答

45

据我所理解,您需要根据文本长度将文本适应于行内。

工作代码:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Icon(Icons.arrow_back),
    Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(Icons.account_box),
          Flexible(
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: Text(
                "  Text HereSome Text Here Text HereSomext HereSome TText HereSome Text HereSome Text HereSome Text HereSome Text HereSome TText HereSome Text HereSome Text HereSome",
                maxLines: 1,
              ),
            ),
          )
        ],
      ),
    ),
    Icon(Icons.arrow_forward),
  ],
);

输出,长文本:

输入图像描述此处

输出,短文本:

输入图像描述此处


1
你是否只想使用FittedBox来适应同一行的文本?或者,如果您需要将文本适配或包装到单行中,则需要将Text包装在Flexible小部件内,该小部件基本上会紧密适应子元素。
我重新创建了您的情况,并能够实现以下结果:

enter image description here

上述代码如下:
Row(
      children: [
        Icon(Icons.arrow_back),
        Expanded(child: SizedBox()),
        Icon(Icons.account_box),
        Flexible(
        child:
        Text("Some Text Here and here and here and here and more and more and more and more and more and more ", maxLines: 1)), // ➜ This is the text.
        Expanded(child: SizedBox()),
        Icon(Icons.arrow_forward),
      ],
      )

由于您将maxLines设置为1,因此它将正确显示您的原始文本Some text here,并且不会发生溢出。如果您添加更多文本,则不会展开该行并且会防止溢出。


谢谢你的答复。我的问题只是当文本太大无法适应空间时使用了FittedBox,我将采用anmol.majhail的解决方案。 - MarcG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接