如何将小部件在堆栈中垂直或水平居中?

时间:2020-07-17 18:06:20

标签: flutter flutter-layout flutter-widget

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),
          ),
        ],
      ),
    );

在行中水平居中:

Horizontally centered widget in Stack

Row(mainAxisAlignment: MainAxisAlignment.center)

与列垂直居中

Vertically centered Widget in Stack

Column(mainAxisAlignment: MainAxisAlignment.center)

上面的对齐是所需的结果。可以用其他Flutter小部件来获得那些结果吗?

1 个答案:

答案 0 :(得分:3)

使用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

3。对于底部中心,请使用对齐方式: Alignment.bottomCenter

enter image description here