本文介绍了CrossAxisAlignment 不居中列小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Flutter 的新手,我一直试图将我的列小部件居中以了解布局,但 Column 的 CrossAxisAlignment 属性似乎不起作用.

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.

我尝试将列封装到其他几个小部件(如容器)中,但到目前为止我发现的解决方案只是覆盖了 CrossAxisAlignment 属性的核心功能.如果我将整个 Column 包装在 Center 小部件中,则默认情况下它以水平轴为中心,CrossAxisAlignment 属性将不起作用.

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.

我找到的唯一解决方案是将列包装在容器中并将其宽度属性设置为占据屏幕的整个宽度,但这似乎是强制布局而不是使用 Flutter 的动态行为.

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

输出:

只有硬设置宽度属性才能正确居中

Only by hard setting the width property does it center properly

Container(
   width: MediaQuery.of(context).size.width,

输出:

我的问题是有没有更好的方法来使用 CrossAxisAlignment 属性而无需手动固定宽度?在哪些用例中它实际上可以在没有任何包装代码的情况下工作?

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?

推荐答案

问题是:CrossAxisAlignment 有效,但您的列仅与图像上显示的一样宽.这样看起来就像什么都没有发生.

The thing is: the CrossAxisAlignment works, but your column is only as wide as it shows on the image. This way it looks like nothing is happening.

要将您的项目放在屏幕的中心,您必须将整个列移动到中心.您可以通过将列包装在 Align 小部件中并设置 alignment: Alignment.center 来实现此目的.

To get your items in the center of the screen, you have to move your entire Column to the center. You can achieve this by wrapping your column inside an Align widget and setting alignment: Alignment.center.

这篇关于CrossAxisAlignment 不居中列小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 13:24