dart ternary code example

Example 1: dart ternary operator

If you're referring to else if statements in 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();

Example 2: dart ternary

int minVal = (a < b) ? a : b;	// if(a < b) {minVal = a;} else {minVal = b;}

var x = y ?? z;  				// assign y to x if y is not null, else z
var x ??= y;    				// assign y to x only if x is null
myObject?.myProp				// (myObject != null) ? myObject.myProp : null
myObject?.myProp?.someMethod()  // chainable

Tags:

Misc Example