thumbnail

Conditional Operators In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Conditional Operators

Conditional operators can be used in place of if else statements.

Using conditional operators you can evaluate expressions based on conditions similar to if else statements.

Conditional Operators in Dart

Shift operators help you to shift binary bits of an integer to left or right as shown in folliwng table.

Operator Description
condition?exp1:exp2; If condition is true then evaluates exp1 otherwise evaluates exp2
exp1??exp2 if exp1 is non null then evaluates and returns its value otherwise evaluates and returns value of exp2

Program using conditional operator ?:

Program given below demonstrates how to use first conditional operator ?:.

main(List<String> args) {
  // if true, evaluates first expression
  print(true ? 'hello' : 'good bye');
  // if false, evaluates the 2nd expression
  print(false ? 'hello' : 'good bye');

  bool summer = true;
  var message = summer ? 'hot' : 'cold';
  print(message);
}

Above program produces following output:

hello
good bye
hot

Program using conditional operator ??

Program given below demonstrates how to use second conditional operator ??.

main(List<String> args) {
  // if first expression is not null then evaluates and returns its value
  // otherwise evaluates second expression and returns its value
  print(null ?? 1);
  print(1 ?? null);
  print(1 ?? 2);
  print(false ?? 1);
}

Above program produces following output:

1
1
1
false

As shown in above programs, conditional operators can be helpful in evaluating various conditions based on expressions.

We hope that you have found this guide useful for learning how to use conditional operators in Dart.