Bill Tertis
Bill Tertis

Reputation: 207

How to return Nothing?

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?

enter image description here

Upvotes: 6

Views: 4717

Answers (3)

Abdul
Abdul

Reputation: 96

Just Return SizedBox() whenever you want to return empty widget.

return SizedBox.shrink();

OR

return SizedBox();

This is efficient way to return nothing except null use if return is required.

Upvotes: 1

Gwhyyy
Gwhyyy

Reputation: 9166

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:

https://pub.dev/packages/nil

A package that provides a low expensive widget that just take place but it's nothing in widget tree paint.

Upvotes: 2

venir
venir

Reputation: 2087

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:

  1. I'd write SizedBox.shrink() instead of Container() inside your else 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;
  2. 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 its mainAxisAlignment to MainAxisAlignment.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.

Upvotes: 9

Related Questions