Flutter Container() vs SizedBox() for dummy empty

How about the Placeholder widget? The name itself indicates your use with it and it also has a const constructor. Though by default, it draws a gray X, but when you give it transparent as its color, that is solved as well.

return _isLoaded ? const Placeholder(color: Colors.transparent) : LoaderWidget();

You can use the Visibility widget, which will use SizedBox for the replacement as default.


In case of use as a placeholder:

Container if the widget has no child, no height, no width, no constraints, and no alignment, but the parent provides bounded constraints, then Container expands to fit the constraints provided by the parent.

SizedBox if the widget has no child, no height, no width, then width and height are zero.

Therefore, SizedBox() serves more as a syntactic placeholder.

Also, note that SizedBox() is a const constructor but Container() is not. The first one allows the compiler to create more efficient code.


regarding that Container() class(widget) has more properties and methods, instantiating it will be a little more costly, so you are right using SizedBox is more efficient. better yet, when you want to have a dummy empty widget use Nil widget. SizedBox 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()).

Tags:

Dart

Flutter