我们可以让Row小部件的两个孩子采用他们想要的宽度(以显示内容而不会溢出),并将剩余空间留给第三个孩子吗?

问题描述 投票:0回答:1

我有三个Text小部件,它们显示在ListTile标题的Row(分别为firstnamemiddlenamelastname)中。 我希望姓氏和名字都必须输入,中间名占用其余空间,如果空间不足以显示完整的中间名,则中间名应该显示省略号

正如您在下图中所看到的,这就是我想要实现的结果。

enter image description here

现在,我将Expanded与中间名一起使用,并让其他名称具有所需的宽度。通过使用下面的代码

ListTile(
    title : Row(
         children<widget> : [
             Text("First Name"),
             Expanded(
                 child : Text("Middle name", overflow : TextOverflow.ellipsis)
             ),
             Text("Last Name"),
         ]
    )
)

但是通过使用上面的代码,如果屏幕的宽度足以容纳所有名称,则中间名会占用多余的空格,如下图所示。

enter image description here

我应该怎么做才能显示名字和姓氏,但要把其余的空格留给中间名

谢谢!

flutter dart flutter-layout
1个回答
0
投票

而不是使用Expanded,您应该使用Flexible小部件,因此您的最终代码应该是

ListTile(
    title : Row(
         children<widget> : [
             Text("First Name"),
             Flexible(
                 child : Text("Middle name", overflow : TextOverflow.ellipsis)
             ),
             Text("Last Name"),
         ]
    )
)

因此,基本上扩展的窗口小部件将占据所有剩余空间,而Flexible将仅占据所需的空间。


0
投票

我不确定这是否适用于每种情况,但是您可以结合使用flex属性来创建效果:

  fullName(String firstName, String middleName, String lastName) {
    var style = TextStyle(
      fontSize: 36.0,
    );

    return Row(
      children: <Widget>[
        Text(
          firstName,
          style: style,
        ),
        Expanded(
          flex: 1,
          child: Text(
            " $middleName ",
            style: style,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Expanded(
          flex: 5,
          child: Text(
            lastName,
            style: style,
          ),
        ),
      ],
    );
  }

对于此示例:

Column(
  children: <Widget>[
    fullName("Ricardo", "", "Markiewicz"),
    fullName("Ricardo", "F.", "Markiewicz"),
    fullName("Ricardo", "Federico", "Markiewicz"),
  ],
)

我得到的结果看起来像这样:

enter image description here

为了获得更准确的用例结果,我认为没有适合该用例的小部件。您可能需要创建自己的小部件,以检查可用宽度并在字符串的中间进行省略号。

© www.soinside.com 2019 - 2024. All rights reserved.