Flutter:SizedBox与Container,为什么要使用其中一个而不是另一个?
问题内容:
当我开始考虑这两个组成部分时,我发现自己在争论为什么我应该一个而不是另一个。我想到了一些问题:
-
Container和SizedBox有什么区别?
-
我知道Container可以具有其他参数,例如padding或装饰,但是如果我不使用这些参数,为什么我应该使用SizedBox而不是Container?
-
它们之间有性能差异吗?
问题答案:
多亏了开源的魔力,您不必猜测太多。
Container
基本上只是一个便利小部件,有时可以使您节省嵌套其他4个小部件的时间。如果您将宽度/高度传递给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与a几乎相同SizedBox
,只是更加灵活。
A SizedBox
会做:
@override
RenderConstrainedBox createRenderObject(BuildContext context) {
return RenderConstrainedBox(
additionalConstraints: _additionalConstraints,
);
}
BoxConstraints get _additionalConstraints {
return BoxConstraints.tightFor(width: width, height: height);
}
即。实际上是一样的。如果仅Container
用于宽度/高度,则性能开销可能很小,可以忽略不计。但您肯定会无法测量。.但我仍然建议您这样做,SizedBox
因为它更清晰。恕我直言。