Flutter: SizedBox Vs Container, why use one instead of the other?

后端 未结 2 1087
长发绾君心
长发绾君心 2020-12-29 01:21

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. W

相关标签:
2条回答
  • 2020-12-29 01:59

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

    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,
    

    Which will result in:

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

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

    A SizedBox will do:

      @override
      RenderConstrainedBox createRenderObject(BuildContext context) {
        return RenderConstrainedBox(
          additionalConstraints: _additionalConstraints,
        );
      }
    
      BoxConstraints get _additionalConstraints {
        return BoxConstraints.tightFor(width: width, height: height);
      }
    

    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.

    0 讨论(0)
  • 2020-12-29 02:01

    I'd like to add that SizedBox is not only simpler, but it also can be made const, while Container cannot. This may or may not be something you need.

    If you need a box with color you cannot use SizedBox. But https://pub.dev/packages/assorted_layout_widgets has the Box widget, which is something between a SizedBox and a Container: You can have color and it can be made const. Note I am the author of this package.

    0 讨论(0)
提交回复
热议问题