I have String variable ‘sdesc1’. Now this variable could either have a value or it could be empty. I am using a container to display the above variable.
....
,
Container(
width: double.infinity,
color: Colors.transparent,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(sdesc1,
style:
TextStyle(fontSize: 10, fontStyle: FontStyle.italic)),
),
),
....
In the app screen, the above code generates a blank row occupying some height when the variable ‘sdesc1’ is empty which is not desirable.
I tried to move the piece of code in a widget method and return the container, but it showed me an error saying that return type could be null some thing like that.
How can I make a container conditional when the variables are empty. Please help with some codes. Thanks in advance.
2
Answers
This condition in the build method can prevents from creating a container (I guessed sdesc1 was a string):
In addition to VincentDR’s answer, you may sometimes find situations where you cannot use if() statements as he showed in his answer. In this case you can use if statement this way:
here is another example in where you would use that:
Also, another way to replace the text if its return is nullable is to use
??
so if you prefer to keep the container there even if there is no text, you can do this: