【问题标题】:How to vertically or horizontally center a Widget in a Stack?如何在堆栈中垂直或水平居中小部件?
【发布时间】:2020-11-07 14:08:02
【问题描述】:

Center 小部件将小部件水平和垂直居中在堆栈的中心。如何才能使小部件仅水平或垂直居中?

使用 Row 或 Column 小部件可以使小部件在 Stack 中居中。不使用这些小部件可以做到吗?

条件:

  • 不能使用行/列。
  • 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),
          ),
        ],
      ),
    );

水平居中 w/Row:

Row(mainAxisAlignment: MainAxisAlignment.center)

垂直居中/列:

Column(mainAxisAlignment: MainAxisAlignment.center)

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

【问题讨论】:

    标签: flutter flutter-layout flutter-widget


    【解决方案1】:

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

    2。对于左中使用对齐方式: Alignment.centerLeft

    3.居中右对齐: Alignment.centerRight

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

    【讨论】:

    • 感谢您的回答!您是否有建议将位置设置为“中心左侧 50 像素”?
    • 另外,是否有类似于 Android 的约束布局属性的基于约束的解决方案?
    • 目前还没有这样的小部件,但您可以将位置与 MediaQuery 一起使用,它在所有设备上的行为都相同。
    猜你喜欢
    • 2021-03-09
    • 2020-10-19
    • 2014-03-16
    • 2017-08-24
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多