如何在Flutter中将一个小部件对齐到屏幕顶部,并将另一个小部件居中对齐到屏幕中间?

时间:2019-02-17 23:49:54

标签: dart flutter flutter-layout

在同一体内,我试图将一个小部件对准屏幕顶部,将另一个小部件对准屏幕中心。事实证明这很困难。

这是我的代码:

body: Column(children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              color: Colors.redAccent,
              width: screenWidth,
              height: 50.0,
              child: Center(
                child: Text(
                  "Hello World!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              color: Colors.blueAccent,
              width: screenWidth,
              height: 50.0,
              child: Center(
                child: Text(
                  "Thanks for the help!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ]),

在我的Xcode模拟器中运行此代码时,结果如下:

https://i.imgur.com/JtPKyq0.png

所以要清楚,这个结果是错误的,因为我希望蓝色容器位于屏幕的中心,而不是顶部。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

一种选择是使用Expanded小部件。该小部件将扩展父级中所有可用的空间,然后将孩子置于其中。请注意,这仅适用于Flex小部件,例如RowColumn等。

对于您而言,我还建议删除行宽的screenWidth变量,并使用Expanded小部件使容器水平填充屏幕。

这是最终代码:

body: Column(children: <Widget>[
    Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded( //makes the red row full width
          child: Container(
            color: Colors.redAccent,
            height: 50.0,
            child: Center(
              child: Text(
                "Hello World!",
                style: TextStyle(
                  fontSize: 18.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    ),
    // This expands the row element vertically because it's inside a column
    Expanded( 
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          // This makes the blue container full width.
          Expanded(
            child: Container(
              color: Colors.blueAccent,
              height: 50.0,
              child: Center(
                child: Text(
                  "Thanks for the help!",
                  style: TextStyle(
                    fontSize: 18.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ]
),