Hello Flutter Folks !!! Hope you guys are enjoying our article based on various topic. In today’s article, we will discuss how to use a ternary operator with multiple conditions in flutter?
Steps to use a Ternary Operator in Flutter App with Multiple Condition?
If you’re referring to else if statements in the dart, then this ternary operator:
(foo==1)? something1():(foo==2)? something2():(foo==3)? something3(): something4();
is equivalent to this:
if(foo == 1){
something1();
}
elseif(foo == 2){
something2();
}
elseif(foo == 3){
something3();
}
else something4();
For three condition user can
value: (i == 1) ? 1 : (i == 2) ? 2 : 0
It is easy,
if(foo == 1 || foo == 2)
{
do something
}
{
else do something
}
It can be written thus for an OR statement.
foo==1 || foo==2 ? do something : else do something
It can be written thus for AND statement
foo==1 && foo==2 ? do something : else do something
Both will work perfectly.
Example
class OperatorExample extends StatefulWidget {
const OperatorExample({Key? key}) : super(key: key);
@override
State createState() => _OperatorExampleState();
}
class _OperatorExampleState extends State {
int x = 20;
int y = 30;
int z = 10;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Ternary with multiple condition"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: RaisedButton(
onPressed: () {
(x >= y && x >= z)
? Fluttertoast.showToast(
msg: "A is Big",
)
: (y >= x && y >= z)
? Fluttertoast.showToast(
msg: "B is Big",
)
: Fluttertoast.showToast(
msg: "C is Big",
);
},
child: const Text('check max number'),
textColor: Colors.white,
color: Colors.blue,
)),
])));
}
}
Output:
Conclusion:
Thanks for being with us Flutter Journey !!!
In this article, we have a walk through using a Ternary Operator with Multiple Condition in flutter?
Drop us if we can help you out with flutter development?
Flutter Agency is one of the leading popular online platform dedicated to Flutter technology and news with daily thousands of unique visitors come to this website to enhance their knowledge on Flutter, learn more about with our Flutter updates and how to article.
Article source: https://flutteragency.com/how-to-use-a-ternary-operator-with-multiple-condition-in-flutter/