如何在 Stack 中垂直或水平居中一个 Widget?

9
Center小部件可以将一个小部件水平和垂直居中于Stack的中心。如何只在水平或垂直方向上居中一个小部件?
使用RowColumn小部件可以将一个小部件置于Stack的中心位置。但是,是否可以不使用这些小部件来完成此操作?
条件:
  • 不能使用Row / Column
  • Stack的大小在布局之前未知(不能使用硬编码的Positioned值)。
Center小部件:

Centered Widget in Stack

Container(
      decoration:
          BoxDecoration(border: Border.all(color: Colors.black87, width: 10)),
      child: Stack(
        children: [
          Center(
            child: Container(color: Colors.amber, width: 50, height: 50),
          ),
        ],
      ),
    );

使用Row使控件水平居中:

Horizontally centered widget in Stack

Row(mainAxisAlignment: MainAxisAlignment.center)

使用Column使控件垂直居中:

Vertically centered Widget in Stack

Column(mainAxisAlignment: MainAxisAlignment.center)

以上对齐方式是期望的结果。这些结果可以在其他Flutter小部件中实现吗?

1个回答

14

使用 Align 小部件

 Align(
        alignment: Alignment.topCenter, // This will horizontally center from the top
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black87, width: 10)),
          child: Stack(
            children: [
              Container(color: Colors.amber, width: 50, height: 50),
            ],
          ),
        ),
      )

1. 顶部中央使用对齐方式: Alignment.topCenter

enter image description here

2. 左侧中央使用对齐方式: Alignment.centerLeft

enter image description here

3. 右侧中央使用对齐方式: Alignment.centerRight

enter image description here

4. 底部中央使用对齐方式: Alignment.bottomCenter

enter image description here


谢谢回答!您有没有关于将位置设置为“中心左侧50像素”的建议? - Ray Li
另外,是否有基于约束的解决方案类似于Android的约束布局属性? - Ray Li
1
目前还没有这样的小部件,但您可以使用MediaQuery中的Positions,在所有设备上都会表现相同。 - Jitesh Mohite

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