CrossAxisAlignment does not center column widgets

Par*_*hit 7 dart flutter flutter-layout

I am new to flutter and I have been trying to center my column widgets just to grasp an understanding of the layouts but the CrossAxisAlignment property of the Column doesn't seem to work.

I have tried enclosing the column into several other widgets like container but the solutions I have found so far just overwrite the core functionality of CrossAxisAlignment property. If I wrap the entire the Column in a Center widget then it is centered on the horizontal axis by default and CrossAxisAlignment property wouldn't work.

The only solution I found was to wrap the column in a container and setting its width property to take up entire width of the screen but that seems like brute forcing the layout instead of using the dynamic behaviour of Flutter.

Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        leading: Icon(
          Icons.arrow_back_ios,
          color: Colors.black,
        ),
      ),
      body: Container(
      color: Colors.grey[500],
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            color: Colors.orange,
            child: FlutterLogo(
              size: 60.0,
            ),
          ),
          Container(
            color: Colors.blue,
            child: FlutterLogo(
              size: 60.0,
            ),
          ),
          Container(
            color: Colors.purple,
            child: FlutterLogo(
              size: 60.0,
            ),
          ),
        ],
      ),
    )
);
Run Code Online (Sandbox Code Playgroud)

Output:

列不居中

Only by hard setting the width property does it center properly

Container(
   width: MediaQuery.of(context).size.width,
Run Code Online (Sandbox Code Playgroud)

Output:

列居中

My question is is there a better way to use CrossAxisAlignment property without manually fixing the width? And in what use cases does it actually work without any wrapper code?

Noo*_*les 7

问题是:CrossAxisAlignment作品,但你的专栏只有它在图像上显示的那么宽。这样看起来好像什么都没发生。

要使您的项目位于屏幕中央,您必须将整个列移动到中央。您可以通过将您的列包装在一个Align小部件中并设置alignment: Alignment.center.


And*_*sky 3

添加alignment

body: Container(
    alignment: Alignment.topCenter, ...
Run Code Online (Sandbox Code Playgroud)