How to use Conditional Statement (IF ELSE) on Child Widget in Flutter
During building an app, sometimes we need to show content according to condition using if..else statement. But in Flutter, we can’t place if…else statement directly on child attribute because it accepts only widgets. But you can apply conditions child attribute like shown in the example below.
bool loading = true;
Container(
child: loading? //check if loading is true or false
CircularProgressIndicator(): //show progress on loading = true
Text("Loaded"), //show this text on loading = false
)
Using Multiple Conditions:
bool loading = false;
bool error = true;
Container(
child: loading? //first check if loading is true or false
CircularProgressIndicator(): //show progress on loading = true
error?Text("Error"): //when loading = false, and then check error is true or false
Text("Loaded and No Error"), //if loading = false and error = false, then show this text
)
Another Example:
int y = 5;
Container(
child: y >= 10?
Text("Y is greater than or equal to 10"):
Text("Y is less than 10")
)
int a = 10;
Column(
children: [
if(a > 10)...[
Text("A is greater than 10"),
]else...[
Text("A is less than or Equal to 10")
]
])
You can apply this method of conditional statement on widget tree which has "children" property, for example, Column(), Row(), Wrap() widgets.
int y = 5;
Container(
child:LayoutBuilder(builder: (context, constraints) {
if(y >= 10){
return Text("Y is greater than or equal to 10");
}else{
return Text("Y is less than 10");
}
})
)
class _MyAppState extends State<MyApp> {
int y = 5;
@override
Widget build(BuildContext context) {
return Scaffold(
body: showwidget()
);
}
showwidget(){
if(y >= 10){
return Text("Y is greater than or equal to 10");
}else{
return Text("Y is less than 10");
}
}
}
In this way, you can use conditional statements, comparisons in child property, or on any widget in Flutter.
Please Wait...
No any Comments on this Article