i have a Widget build(BuildContext context)
which returns some Container
with elements inside, but when 'else' comes in the end in some cases i dont want to return an empty Container because it still takes some space. how can i remove these spaces?
CodePudding user response:
Container
imposes zero constraints on its children and tells no information about its size to its parent.
If you're confused by this statement, before continuing reading, read this Flutter's documentation page about layouting.
This being said, I would do the following:
- I'd write
SizedBox.shrink()
instead ofContainer()
inside yourelse
clause. This widget tells its parent that he wants to be of size "zero" (as you've requested). NOTE. This is just for readability purposes. A parent can still force a minimum height or width onto its children; - I'd check the constraints and / or the layouting your parent widget forces onto children. For example, if it's a
Column
, then I'd set itsmainAxisAlignment
toMainAxisAlignment.start
so that now no space is supposed to be inserted between its children. There are way more possible cases though (probably infinite), so further investigation should be done.
Hope this helps.
CodePudding user response:
even though the previous answer is totally fine and true.
but the flutter engine will configure and paint any widget on the screen even if it's empty, using SizedBox
will still need to be painted and assigned to the widget tree even if it's empty. so it's not the performant way to do it
I asked the same thing a time, I searched then I found this:
A package that provides a low expensive widget that just take place but it's nothing in widget tree paint.