Conditional expressions

Dart has two operators that let you concisely evaluate expressionsthat might otherwise require if-else statements:

  • condition ? expr1 : expr2
  • If condition is true, evaluates expr1 (and returns its value);otherwise, evaluates and returns the value of expr2.
  • expr1 ?? expr2
  • If expr1 is non-null, returns its value;otherwise, evaluates and returns the value of expr2.

When you need to assign a valuebased on a boolean expression,consider using ?:.

  1. var visibility = isPublic ? 'public' : 'private';

If the boolean expression tests for null,consider using ??.

  1. String playerName(String name) => name ?? 'Guest';

The previous example could have been written at least two other ways,but not as succinctly:

  1. // Slightly longer version uses ?: operator.
  2. String playerName(String name) => name != null ? name : 'Guest';
  3. // Very long version uses if-else statement.
  4. String playerName(String name) {
  5. if (name != null) {
  6. return name;
  7. } else {
  8. return 'Guest';
  9. }
  10. }