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

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. What are the differences between a Container and SizedBox?

  2. 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?

  3. There are performance differences between them?



Solution 1:[1]

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.

Solution 2:[2]

SizedBox() is a widget for giving some constant height or width between two widgets. It does not contain any decorative properties just like color, borderRadius etc.

On the other hand Container() is a widget that any person can modify according to his/her needs.

Just go through properties of both widgets you will see a huge difference between them.

Solution 3:[3]

SizedBox and Container creates a RenderObject. The RenderObject lives in the render tree and some computations are performed on it, even if it paints nothing on the screen.

We can do better, we can have a widget which does not create a RenderObject, while being still valid. The Nil widget is the minimal implementation for this use case. It only creates an Element and does nothing while it's building. Because the optimal way to use it, is to call const Nil(), it also comes with a nil constant that you can use everywhere (which is a const Nil()).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Muzammil Hassan
Solution 3 geekymano