为什么Flutter Container在其他Container中时不遵守其宽度和高度限制 [英] Why Flutter Container does not respects its width and height constraints when it is inside other Container

查看:1891
本文介绍了为什么Flutter Container在其他Container中时不遵守其宽度和高度限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Container(
  width: 200.0,
  height: 200.0,
  child: Container(
    width: 50.0,
    height: 50.0,
    decoration: BoxDecoration(
      shape: BoxShape.circle,
      color: Colors.red
    ),
  ),
)

我一直试图在Container类文档中找到答案,但是我没有找到。

I've been trying to find the answer in the Container class docs but I did not find it.

更新:

经过很长时间,我了解了这个问题。

After a long time, I understood the problem.

布局中的所有视图必须具有宽度,高度,x位置和y位置。 (这适用于Android,IOS,Flutter等)

All views inside a layout must have width, height, x position, and y position. (This applies to Android, IOS, Flutter, etc)

在我的代码中,内部容器仅具有宽度和高度,因此它不知道在哪里

In my code, the inner container just has a width and height for that reason it doesn't know where to start painting.

因此,如果将容器放置在对齐小部件内,则容器将获得x位置和y位置,并且可以使用。

For that reason, if the container is placed inside an Alignment widget the container gets the x position and y position and it works.

推荐答案

Flutter中的约束工作原理与平常有所不同。
小部件本身没有约束。

Constraints in Flutter works a bit different than usual. Widgets themselves do not have constraints.

当您指定宽度 / 容器上>高度,您就不必约束容器。您正在约束容器

When you specify a width/height on a Container, you're not constraining Container. You're constraining the child of Container.

容器然后将根据其子项的大小对其自身进行大小调整。

Container will then size itself based on the size of its child.

因此,父级窗口小部件始终对后代的大小起最后决定作用。

As such, parent widgets always have the last word on how their descendants should be sized.

如果要解决此问题,必须使用 Align 小部件:

If you want to go around this, you have to use Align widget:

Container(
  width: 200.0,
  height: 200.0,
  child: Align(
    alignment: Alignment.topLeft,
    child: Container(
      width: 50.0,
      height: 50.0,
      decoration:
          BoxDecoration(shape: BoxShape.circle, color: Colors.red),
    ),
  ),
);






这似乎很奇怪并且有局限性。但是这种奇怪的感觉是Flutter的布局如此强大且可组合的原因。


This may seem weird and limiting. But this single weirdness is the reason why Flutter's layout is so powerful and composable.

这篇关于为什么Flutter Container在其他Container中时不遵守其宽度和高度限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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