Conditional Expressions

Conditional expressions in Dart provide a concise way to make decisions in your code. They're like shortcuts for simple if-else statements, making your code more readable and compact.

Ternary Operator (?:)

The ternary operator is the most common conditional expression. It follows this pattern:

condition ? valueIfTrue : valueIfFalse

Think of it as asking a question: "Is this condition true? If yes, use this value. If no, use that value."

void main() {
  int age = 18;
  String status = age >= 18 ? 'Adult' : 'Minor';
  print(status); // Output: Adult
  
  int score = 85;
  String grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
  print(grade); // Output: B
}

Null-aware Operators

Dart provides special operators to handle null values gracefully.

?? (Null Coalescing Operator)

This operator returns the left operand if it's not null, otherwise returns the right operand.

void main() {
  String? name = null;
  String displayName = name ?? 'Guest';
  print(displayName); // Output: Guest
  
  String? username = 'john_doe';
  String user = username ?? 'Anonymous';
  print(user); // Output: john_doe
}

??= (Null Assignment Operator)

This operator assigns a value only if the variable is currently null.

void main() {
  String? message;
  message ??= 'Default message';
  print(message); // Output: Default message
  
  message ??= 'Another message';
  print(message); // Output: Default message (unchanged)
}

?. (Null-aware Access Operator)

This operator safely accesses properties or methods of an object that might be null.

void main() {
  String? text = null;
  int? length = text?.length;
  print(length); // Output: null
  
  String? greeting = 'Hello';
  int? greetingLength = greeting?.length;
  print(greetingLength); // Output: 5
}

Practical Examples

Here are some real-world scenarios where conditional expressions shine:

void main() {
  // Setting default values
  int? userAge;
  int displayAge = userAge ?? 0;
  
  // Formatting output
  double price = 29.99;
  String formattedPrice = price > 0 ? '\$${price.toStringAsFixed(2)}' : 'Free';
  print(formattedPrice); // Output: $29.99
  
  // Validation
  String email = '[email protected]';
  bool isValid = email.contains('@') ? true : false;
  print('Email valid: $isValid'); // Output: Email valid: true
  
  // Safe method calls
  List<String>? items = ['apple', 'banana'];
  String firstItem = items?.isNotEmpty == true ? items!.first : 'No items';
  print(firstItem); // Output: apple
}

Comparison with If-Else

Here's how conditional expressions compare to traditional if-else statements:

Conditional ExpressionIf-Else Statement
int result = x > 0 ? 1 : -1;int result; if (x > 0) { result = 1; } else { result = -1; }
String msg = name ?? 'Unknown';String msg; if (name != null) { msg = name; } else { msg = 'Unknown'; }

Conditional expressions are perfect for simple decisions and assignments, while if-else statements are better for complex logic with multiple statements.

Remember: Use conditional expressions to make your code more concise, but don't sacrifice readability. If the logic becomes too complex, stick with traditional if-else statements!