Flutter - 如何创建宽度与父容器相同的Container?

50

我在我的Flutter应用程序中使用这个简单的小工具:

  FlatButton(
   child: Column(
          children: <Widget>[
            Image.asset(assets, height: 40, width: 40),
            Text('Title'),
            //my color line
            Container(
              height: 5,
              width: ?,
              color: Colors.blue[800],
            )
          ],
        )
  )

我需要底部的彩色线条,宽度与父元素相匹配。但我不知道该如何实现。


你尝试将其设置为 double.infinity 了吗? - Kamil Rykowski
你想让蓝线与图片一样大吗?还是想让线的宽度与按钮一样?如果是这种情况,只需删除宽度参数即可。 - Sergio Bernal
4个回答

67
Container(
    height: 5,
    width: double.infinity,
    color: Colors.blue[800],
)

1
这个答案有什么问题吗?我喜欢它的简洁性。 - Dan Maia
这个答案并没有错,这就是问题所在。我测试了想要创建一个只有形状和填充大小的容器,但这行不通。 - undefined

41

使用IntrinsicWidth

 FlatButton(
   child: IntrinsicWidth(
   child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Image.asset(assets, height: 40, width: 40),
            Text('Title'),
            //my color line
            Container(
              height: 5,
              width: ?,
              color: Colors.blue[800],
            )
          ],
        ))
  )

一些快捷表


15

有两种方法可以做到这一点

ConstrainedBox:

它创建一个小部件,对其子项施加额外的约束条件,内部使用SingleChildRenderObjectWidget在子小部件上添加约束条件。

ConstrainedBox(
        constraints:
            const BoxConstraints(minWidth: double.infinity, maxHeight: 10),
        child: Container(
          color: Colors.blue,
        ),
      ),

SizedBox:

SizedBox 可以简单创建一个指定宽度/高度的盒子,并且不允许子元素超出指定的尺寸范围。它还使用 SingleChildRenderObjectWidget 来确定子元素绘制区域。

SizedBox(
        width: double.infinity,
        height: 5,
        // height: double.infinity,
        child: Container(
          color: Colors.blue,
        ),
      ),

3
在没有子元素的Column中,Container将始终扩展。如果添加了child,则会将其包装起来。
此外,如果您没有在按钮中限制Column,它也会增长到可用高度的最大值。
建议您改用一个带有底部边框的Container来包含按钮,而不是将空的Container放在按钮的Column中。这将为您提供底部的彩色线条。
Container(
  decoration: BoxDecoration(
    border: Border(
      bottom: BorderSide(width: 5, color: Colors.blue[800]),
    ),
  ),
  child: FlatButton(
    onPressed: () {},
    child: Column(
      mainAxisSize: MainAxisSize.min, // prevent Column to expand full height
      children: <Widget>[
        Icon(Icons.cake, size: 40),
        Text('title'),
      ],
    ),
  ),
),

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