In addition to the standard conditional operators, Dart has a couple which, while standard are not used as often as used forms of conditions, such as the switch and the Ternary operator which we’ll see in a minute.
The Switch
The switch is a tool which when it can be applied allows for efficient checking of multiple options. However, because it is needing an exact match, it can be difficult to find the right use.
It uses the switch keyword, and then in parenthesis what is being checked against. Within the body of the switch, are case statements that you can use to identify matches. See below for an example.
switch(testValue) {
case 0:
// do stuff if testValue was equal to 1
break;
case 1:
// do stuff if testValue was equal to 2
break;
case 2:
// do stuff if testValue was equal to 3
break;
default:
// do stuff if there wasn't a match
break;
}
The Ternary Operator
This is a short=hand form of an if else statement. It uses only a ? and a : to create the if else statement, and it has to have both a true and false block. The blocks need to be short, ideally a small line of code.
Overall, most people avoid it, as while it is shorter to write, it doesn’t help with clarity of the code, and thus can lead to other issues.
The ? separates the condition from the true “block”.
The : separates the true and false blocks. The general form is below:
<condition> ? <true statement> : <false statement>;
The true and false statements can be stored in a variable, or they can be something that is done.
void sample(int x, int y) {
x < y ? print("smaller") : print("bigger");
}
void sample2(int x, int y) {
var answer = x < y ? "smaller" : "bigger";
print(answer);
}
Additionally, Dart provides a second ternary use, which is not seen as often in other languages.
expr1 ?? expr2
If expr1 is non-null, its value is returned; otherwise, the value of expr2 is evaluated and returned.
void main() {
var n1 = null;
var n2 = 2;
var res = n1 ?? n2;
print(res);
}
Advanced Conditions in Dart was originally found on Access 2 Learn
One Comment
Comments are closed.