Nothing was causing any problems but I was kind of curious...
In flutter, if you write a code like this:
child: Container(
height: 20,
child: Container(), // could be any widget
),
it gives a warning of SizedBox for whitespace.
.
But why does this warning not show when I do this?
child: Container()
I see many codes where Container()
is returned when not to show something.
CodePudding user response:
The warning you are seeing when using a nested Container
with a fixed height is suggesting that you use a SizedBox
widget instead. This is because a SizedBox
is a more efficient way to create fixed-size widgets, as it doesn't involve creating an unnecessary RenderBox
in the rendering tree.
A Container
is a heavier Widget than a SizedBox
, and as bonus, SizedBox
has a const constructor. - Lint Rule
On the other hand, when you use a single Container
without a fixed size, there is no need to use a SizedBox
, as the Container
itself does not create a fixed-size widget. In this case, the Container
will take up only as much space as it needs to render its contents.
It is common to see a single Container
used as a placeholder or as a simple container for other widgets. In these cases, using a SizedBox
would not make sense, as it would unnecessarily add more complexity to the layout.
It is worth noting that the warning you are seeing is just a suggestion and not a hard rule. You can choose to ignore the warning and use a nested Container
with a fixed size if it is the most appropriate solution for your use case.
CodePudding user response:
Flutter's new version suggests using SizedBox for whitespace (spaces that contain nothing or only a given width or height and nothing else).
This way you can have a clean specific function for your widget.
With the Container widget, you are more functionality like color, decoration etc.c
CodePudding user response:
The reason why empty Container() does not raise a warning is because it is a valid widget, and no errors are raised when it is called. This is because an empty container is an empty space, and this is a valid use case in UI design. Additionally, Flutter is designed to be flexible and is designed to be able to handle all sorts of UI designs. Therefore, Flutter does not raise a warning for empty Container().