【问题标题】:How to make the width of a container match its height如何使容器的宽度与其高度匹配
【发布时间】:2019-12-04 10:52:37
【问题描述】:

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

【问题讨论】:

  • 使用AspectRatio
  • @CopsOnRoad 它是为这种情况而设计的:“尝试将孩子调整为特定纵横比的小部件。”
  • @pskink 我想我应该将它包含在我的解决方案中,但已经有人回答了。
  • @CopsOnRoad 继续并将其添加到您的 amswer

标签: flutter flutter-layout


【解决方案1】:

为此,您必须使用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),
)

【讨论】:

    【解决方案2】:

    宽高比会起作用

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

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 2023-04-03
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多