Taufik Nur Rahmanda
Taufik Nur Rahmanda

Reputation: 1969

Flutter Container() vs SizedBox() for dummy empty

I am curious about this. I have seen many example using Container() for dummy hidden widget, for example, when loading has completed, then we setState(() { _isLoaded = true; });. So we can use the state like this, right?

return _isLoaded ? Container() : LoaderWidget();

Or maybe using SizedBox() is actually better because it don't take much parameters and often used for padding anyway?

return _isLoaded ? SizedBox() : LoaderWidget();

Or am I wrong?

Upvotes: 15

Views: 16374

Answers (4)

Moji
Moji

Reputation: 1830

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()).

Upvotes: 7

bear
bear

Reputation: 126

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();

Upvotes: 1

Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15945

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

Upvotes: 1

Spatz
Spatz

Reputation: 20148

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.

Upvotes: 39

Related Questions