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

Ray*_* Li 4 flutter flutter-layout flutter-widget

Center部件在堆叠的中心部件水平和垂直中心。如何仅水平或垂直居中小部件?

使用行或列小部件可以使堆栈中的小部件居中。可以在不使用这些小部件的情况下完成吗?

状况:

  • 不能使用行/列。
  • Stack 的大小在布局之前是未知的(不能使用硬编码的 Positioned 值)。

中心小部件:

堆栈中的居中小部件

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

与行水平居中:

堆栈中水平居中的小部件

Row(mainAxisAlignment: MainAxisAlignment.center)

垂直居中与列:

堆栈中垂直居中的小部件

Column(mainAxisAlignment: MainAxisAlignment.center)

上面的对齐是想要的结果。使用其他 Flutter 小部件可以实现这些结果吗?

jit*_*555 5

使用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),
            ],
          ),
        ),
      )
Run Code Online (Sandbox Code Playgroud)

1. 对于顶部中心使用对齐: Alignment.topCenter

在此处输入图片说明

2.对于中心左使用对齐: Alignment.centerLeft

在此处输入图片说明

3. 居中右对齐: Alignment.centerRight

在此处输入图片说明

3.对于底部中心使用对齐: Alignment.bottomCenter

在此处输入图片说明