The Dart ternary operator syntax (examples)

As a quick note, the Dart ternary operator syntax is the same as the Java ternary operator syntax. The general syntax is:

result = testCondition ? trueValue : falseValue

A few examples helps to demonstrate Dart’s ternary syntax:

int a = -1;
int b = 2;

int minVal = (a < b) ? a : b;
print(minVal);   //prints "-1"

int absValue = (a < 0) ? -a : a;
print(absValue);   //prints "1"

Here are some examples of how I use Dart’s ternary operator syntax in Flutter code:

// as a flutter widget property
subtitle: _notificationsAreEnabled ? Text('ON') : Text('OFF'),

Color _rowBgColor(int rowNum) {
    return rowNum % 2 == 0 ? Colors.grey[100] : Colors.white;
}

In summary, if you wanted to see some examples of the Dart ternary operator syntax, I hope this is helpful.