flutter - Flutter 中的对齐属性容器

标签 flutter

Alignment 属性在 Flutter 中的 Container widget 中是如何工作的?我有以下代码,它在容器中没有对齐属性。

return GridTile(
                              child: Column(children: <Widget>[
                      Image.network(_workoutCategories[index].imageURL),
                      Container(  
                        color: const Color(0xffe67e22),
                        child: Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Text(_workoutCategories[index].name, style: TextStyle(color: Colors.white, fontSize: 24)),
                        ),
                      )
                  ]),
              );

结果如下:

enter image description here

当我在容器上添加对齐属性时,容器似乎会拉伸(stretch)以填充父级,如下所示: enter image description here

我认为对齐属性只是用来对齐子部件的。到底是怎么回事?

最佳答案

首先,您必须了解 alignment 属性不是指 Container 对齐,而是指其子项的对齐。

想象一下,定义 child 对齐方式的是它接触的角。如果您将其向左对齐,则 child 将触摸左角。但是,如果父对象没有填满所有可用空间,则子对象无法正确对齐,因为如果父对象占用尽可能少的空间,则子对象会触及父对象的所有角落。这就是为什么 Container 必须在您设置对齐方式时填充所有空间,否则 child 将无法遵守该对齐方式。

在您的情况下,如果您不希望橙色框填满所有空间并仍然位于中心,则将其包装在另一个居中对齐的容器中:

Container(
  alignment: Alignment.center,
  Container(
    color: const Color(0xffe67e22),
    child: Padding(
      padding: const EdgeInsets.all(10.0),
      child: Text(_workoutCategories[index].name, style: TextStyle(color: Colors.white, fontSize: 24)),
    ),
  ),
)

关于flutter - Flutter 中的对齐属性容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56262634/

相关文章:

Flutter TextField 电话号码建议?

function - 使用功能在 flutter 中添加多个图像?

flutter - 为什么在flutter中使用provider时不执行class的构造函数?

iOs 构建失败,FacebookLogin 包

flutter - 我可以使用flutter的TabBar来过滤卡片列表吗?

dart - 使用嵌套数组列表将字符串转换为 Json

user-interface - Flutter tabBar如何上下变化

flutter - 属性 android :requestLegacyExternalStorage not found flutter imagepicker

class - 如何从Flutter中的另一个类访问一个类的变量

android - Flutter:TextFormField 图标下方的下划线