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?
-
1empty Containers do not take any space. What you see must be whatever you put the empty Container in– IvoSep 30, 2022 at 12:18
-
1Why do you need to return something? If this is in the children: list of some multiwidget layout thing, just use collection literal "if" syntax to remove the element if not needed.– Randal SchwartzSep 30, 2022 at 21:24
2 Answers
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.
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.
-
I'm curious about this: how can a render object affect performance that much? Isn't layouting and rendering the bread and butter of Flutter, with its very fast layouting algorithm?– venirSep 30, 2022 at 15:39
-
-
you can see the source code of it, it will make sense after you read it– GwhyyySep 30, 2022 at 18:22