小部件的自定义width / height属性将被忽略 [英] Custom width/height property for a widget are ignored

查看:71
本文介绍了小部件的自定义width / height属性将被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想强制小部件采用特定的大小,通常使用 SizedBox / ConstrainedBox / 容器

Sometimes I want to force a widget to take a specific size, which I usually do by using a SizedBox/ConstrainedBox/Container

但是我已经意识到,在某些情况下,小部件只是忽略了它并采用了不同的大小。为什么?

But I've realized that in some situations, the widget merely ignores it and takes a different size. Why is that?

示例:

预期的行为:

实际行为:

< a href = https://i.stack.imgur.com/vyGxf.png rel = nofollow noreferrer>

推荐答案

这种情况发生在父母和孩子想要两个不同尺寸的情况下;但是父级不知道如何在子域内对齐子级。

This situation happens when the parent and its child wants two different sizes; but the parent has no idea how it should align its child within its boundaries.

以下代码没有提供足够的信息来告诉我们如何在子域内对齐红色框蓝框:

The following code doesn't give enough information to tell how to align the red box within the blue box:

Container(
  color: Colors.blue,
  width: 42,
  height: 42,
  child: Container(
    color: Colors.red,
    width: 24,
    height: 24,
  ),
),

因此,虽然可以居中定位:

So while it could be centered as such:

期望以下对齐方式也是完全合理的:

it would also be perfectly reasonable to expect the following alignment instead:

在这种情况下,颤振不知道如何对齐红色框,它将提供一个更简单的解决方案:

In that situation, since Flutter doesn't know how to align the red box, it will go with an easier solution:

不要对齐红色框,并强迫它占用所有可用空间;会导致:

Don't align the red box, and force it to take all the available space; which leads to:

要解决此问题,解决方案是明确告诉Flutter如何在子级的父边界内对齐子级。

To solve this issue, the solution is to explicitly tell Flutter how to align the child within its parent boundaries.

最常见的解决方案是通过包装将孩子放入 Align 小部件:

The most common solution is by wrapping the child into an Align widget:

Container(
  color: Colors.blue,
  width: 42,
  height: 42,
  child: Align(
    alignment: Alignment.center,
    child: Container(
      color: Colors.red,
      width: 24,
      height: 24,
    ),
  ),
),

某些小部件,例如 Container Stack 还将提供 alignment 属性以实现类似的行为。

Some widgets such as Container or Stack will also offer an alignment property to achieve similar behavior.

这篇关于小部件的自定义width / height属性将被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆