14

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?

Taufik Nur Rahmanda
  • 1,862
  • 2
  • 20
  • 36
  • Possible duplicate of [Flutter: SizedBox Vs Container, why use one instead of the other?](https://stackoverflow.com/questions/55716322/flutter-sizedbox-vs-container-why-use-one-instead-of-the-other) –  Aug 29 '19 at 06:28

4 Answers4

36

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.

Spatz
  • 18,640
  • 7
  • 62
  • 66
  • I was asking myself why in some code people used const to instantiate some classes, now I will definitively search this topic :) Thanks! – funder7 Dec 27 '20 at 21:20
7

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

geekymano
  • 1,420
  • 5
  • 22
  • 53
1

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

Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162
1

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();
bear
  • 96
  • 5