首页 > 解决方案 > 如何使容器的宽度与其高度匹配

问题描述

我有一个Container基于其父级的高度,它Expanded的 flex 为 2。我需要高度和宽度相同。我不想创建固定宽度,例如width: 100.0. 是否可以使宽度与Container内部的高度匹配Expanded

标签: flutterflutter-layout

解决方案


为此,您必须使用LayoutBuilder,这是最少的代码:

Column(
  children: <Widget>[
    Expanded(
      flex: 2,
      child: LayoutBuilder(
        builder: (_, constraints) {
          return Container(
            color: Colors.blue,
            width: constraints.maxHeight, // width is made equal to height
          );
        },
      ),
    ),
    Expanded(
      flex: 9,
      child: Container(color: Colors.orange),
    ),
  ],
)

编辑:正如@pskink 和其他提到的你也可以使用AspectRatio

AspectRatio(
  aspectRatio: 1,
  child: Container(color: Colors.blue),
)

推荐阅读