Im new to flutter, I see I can't use if statement with curly braces but what if I have the below code, do I have to repeat if statement in every widget?
Block1
if(product.length>0)
Container(..)
if(product.length>0)
Divider(..),
block2
else
Container(...)
Expanded(..)
so I can't use curly here but what is the solution for this issue?
CodePudding user response:
You can use Ternary operator. Also you don't need to add if statement above all the widgets, you can add that all widget inside one Column().For example: product.length>0 ? Container() : Column()
CodePudding user response:
You can use if else
statements with and without curly braces.
- Using Curly braces:
if(product.length>0){
// Some other code here
Container(..)
}else{
Placeholder(..)
}
- Without curly braces:
if(product.length>0)
Container(..)
// some code NOTE: THIS IS NOT A PART OF THE IF ELSE STATEMENT
// WITHOUT CURLY BRACES YOU CAN HAVE ONLY ONE STATEMENT INSIDE IF-ELSE
It is always recommended to use curly braces to avoid confusion.
EDIT:
Also a more clean approach would be ternary operators:
return Container(child: product.length>0 ? Text() : Placeholder());
If the condition evaluated to true
then, 1st expression is evaluated and returned, otherwise 2nd expression is evaluated and returned.
You can read more about it here: Conditional Expression - Dart.dev
CodePudding user response:
if you have multiple properties in the same condition then you can wrap those things in a Column
if(length>0)
Column(
children: [
// your widgets
]
)