Flutter:SizedBox与Container,为什么要使用其中一个而不是另一个? [英] Flutter: SizedBox Vs Container, why use one instead of the other?

查看:577
本文介绍了Flutter:SizedBox与Container,为什么要使用其中一个而不是另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始考虑这两个组成部分时,我发现自己在争论为什么我应该一个而不是另一个.我想到了一些问题:

When I start to think about those two componentes I find myself arguing about why should I one instead of the other. Some questions that come to my mind:

  1. Container和SizedBox有什么区别?

  1. What are the differences between a Container and SizedBox?

我了解Container可以具有其他参数,例如填充或装饰,但是如果我不使用这些参数,为什么我应该使用SizedBox而不是Container?

I understand that Container can have other parameters like padding or decoration, but if I will not use those, why should I use a SizedBox instead of a Container?

它们之间有性能差异吗?

There are performance differences between them?

推荐答案

感谢开源的魔力,您不必猜测太多.

Thanks to the magic of open source, you don't have to guess too much.

Container基本上只是一个便捷的小部件,有时它使您无法嵌套其他4个小部件.如果您将宽度/高度传递到Container:

Container is basically just a convenience widget which sometimes saves you to nest 4 other widgets. If you pass width/height into the Container:

       constraints =
        (width != null || height != null)
          ? constraints?.tighten(width: width, height: height)
            ?? BoxConstraints.tightFor(width: width, height: height)
          : constraints,

这将导致:

    if (constraints != null)
      current = ConstrainedBox(constraints: constraints, child: current);

ConstrainedBox实际上与SizedBox相同,只是更加灵活.

And the ConstrainedBox in effect is pretty much the same as a SizedBox, just more flexible.

SizedBox将执行以下操作:

  @override
  RenderConstrainedBox createRenderObject(BuildContext context) {
    return RenderConstrainedBox(
      additionalConstraints: _additionalConstraints,
    );
  }

  BoxConstraints get _additionalConstraints {
    return BoxConstraints.tightFor(width: width, height: height);
  }

即.实际上是相同的.如果仅对宽度/高度使用Container,则可能会产生很小的可忽略的性能开销.但您肯定会无法测量..但我仍然建议SizedBox,因为它更清晰.恕我直言.

ie. It is effectively the same. If you only use Container for width/height there might be a very minor minor negligible performance overhead. but you most certainly will not be able to measure it.. But I would still recommend SizedBox because it's way clearer. imho.

这篇关于Flutter:SizedBox与Container,为什么要使用其中一个而不是另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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