So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):
new Center(
child: condition == true ? new Container() : new Container()
)
Though when I tried using an if/else statement it would lead to an Dead code warning:
new Center(
child:
if(condition == true){
new Container();
}else{
new Container();
}
)
Interestingly enough I tried with a switch case statement and it gives me the same warning and thus I cannot run the code. Am I doing something wrong or is it so that one cannot use if/else or switch statements without flutter thinking there is dead code?
Actually you can use if/else
and switch
and any other statement inline in dart / flutter.
class StatmentExample extends StatelessWidget {
Widget build(BuildContext context) {
return Text((() {
if(true){
return "tis true";}
return "anything but true";
})());
}
}
ie wrap your statements in a function
(() {
// your code here
}())
I would heavily recommend against putting too much logic directly with your UI 'markup' but I found that type inference in Dart needs a little bit of work so it can be sometimes useful in scenarios like that.
condition ? Text("True") : null,
children: [
...manyItems,
oneItem,
if(canIKickIt)
...kickTheCan
for (item in items)
Text(item)
child: getWidget()
Widget getWidget() {
if (x > 5) ...
//more logic here and return a Widget
As another alternative to the ternary operator, you could create a function version of the switch statement such as in the following post https://stackoverflow.com/a/57390589/1058292.
child: case2(myInput,
{
1: Text("Its one"),
2: Text("Its two"),
}, Text("Default"));