当我开始思考这两个组件时,我发现自己在争论为什么我应该 Select 一个而不是另一个.我脑海中浮现出几个问题:
Container和SizedBox有什么区别?
我知道Container可以有其他参数,如填充或装饰,但如果我不使用这些参数,为什么要使用SizedBox而不是Container呢?
它们之间有性能差异吗?
当我开始思考这两个组件时,我发现自己在争论为什么我应该 Select 一个而不是另一个.我脑海中浮现出几个问题:
Container和SizedBox有什么区别?
我知道Container可以有其他参数,如填充或装饰,但如果我不使用这些参数,为什么要使用SizedBox而不是Container呢?
它们之间有性能差异吗?
小更新:When used for whitespace, there is now even a linter warning to prefer SizedBox
instead of Container
.主要优点似乎是SizedBox
可以是const
,甚至不会在运行时创建新实例.
多亏了开源的魔力,您不必猜太多.
Container
基本上只是一个方便的小部件,它有时可以让你省go 嵌套其他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实际上与SizedBox
几乎相同,只是更灵活.
SizedBox
分可以做到:
@override
RenderConstrainedBox createRenderObject(BuildContext context) {
return RenderConstrainedBox(
additionalConstraints: _additionalConstraints,
);
}
BoxConstraints get _additionalConstraints {
return BoxConstraints.tightFor(width: width, height: height);
}
实际上是一样的.如果宽度/高度仅使用Container
,那么性能开销可能非常小.但你肯定无法测量它..但我还是推荐SizedBox
,因为它更清晰.依我拙见