Lesson 10 min

Ternary & Conditional Expressions

00:00 / 00:00

Ternary & Conditional Expressions

Sometimes an if-else block feels like overkill for a simple choice between two values. Dart gives you the ternary operator — a compact, expressive way to write conditional logic in a single line.


🔹 The Ternary Operator

Syntax:

dart
condition ? valueIfTrue : valueIfFalse

It reads like a question: "If condition is true, give me valueIfTrue; otherwise give me valueIfFalse."

dart
void main() { int age = 20; // Using if-else String result1; if (age >= 18) { result1 = 'Adult'; } else { result1 = 'Minor'; } // Using ternary — same logic, one line String result2 = age >= 18 ? 'Adult' : 'Minor'; print(result1); // Adult print(result2); // Adult }

Both produce the same result. The ternary version is shorter and reads naturally once you are familiar with it.


🔹 When to Use Ternary vs if-else

SituationPrefer
Simple value assignment between two optionsTernary ? :
Complex logic with multiple statements per branchif-else
Inline expressions in string interpolationTernary
Readability matters more than brevityif-else
Conditions with side effects (print, API call)if-else

Good Use of Ternary

dart
void main() { int number = 7; // Concise, readable String parity = number % 2 == 0 ? 'Even' : 'Odd'; print(parity); // Odd // Works great inside string interpolation print('The number $number is ${number % 2 == 0 ? "even" : "odd"}.'); }

When if-else Is Better

dart
void main() { bool isLoggedIn = false; // Too many side effects — use if-else if (isLoggedIn) { print('Loading dashboard...'); fetchUserData(); setupNotifications(); } else { print('Redirecting to login...'); clearSession(); } }

🔹 Nested Ternary (and Why to Avoid It)

Technically, you can nest ternary operators:

dart
void main() { int score = 72; // Nested ternary — technically valid String grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F'; print(grade); // C }

Warning: Nested ternaries are hard to read and error-prone. When you need more than two branches, use if-else if or a switch expression instead. Your future self (and your teammates) will thank you.


🔹 Ternary with Null Safety

Dart's null safety pairs beautifully with ternary for concise null handling:

dart
void main() { String? name; // nullable // Check and provide a fallback String displayName = name != null ? name : 'Guest'; print(displayName); // Guest String? city = 'Kolkata'; String location = city != null ? city : 'Unknown'; print(location); // Kolkata }

Tip: For the common pattern of value != null ? value : fallback, Dart provides the even shorter null-coalescing operator ??:

dart
String displayName = name ?? 'Guest';

This is preferred over ternary for null-fallback cases.


🔹 Dart-Specific: Conditional Expressions in Flutter

One of the places ternary truly shines in Dart is inside Flutter widget trees. Because Flutter UIs are built by composing expressions, ternary fits perfectly:

dart
// Flutter preview (requires Flutter SDK) Widget build(BuildContext context) { bool isLoggedIn = false; return Scaffold( body: Center( // Ternary picks the right widget based on state child: isLoggedIn ? const Text('Welcome back, Alice!') : const Text('Please log in.'), ), ); }

Without ternary, you would need an if-else block outside the widget tree and a variable to hold the widget — much more verbose.

Another common Flutter pattern:

dart
Widget build(BuildContext context) { bool isDarkMode = true; return Container( color: isDarkMode ? Colors.black : Colors.white, padding: const EdgeInsets.all(16), child: Text( isDarkMode ? 'Dark Mode Active' : 'Light Mode Active', style: TextStyle( color: isDarkMode ? Colors.white : Colors.black, fontSize: 18, ), ), ); }

🔹 Practical Examples

Example 1: Maximum of Two Numbers

dart
int max(int a, int b) => a > b ? a : b; void main() { print(max(10, 20)); // 20 print(max(50, 30)); // 50 print(max(7, 7)); // 7 }

Example 2: Odd or Even Check

dart
String oddOrEven(int n) => n % 2 == 0 ? 'Even' : 'Odd'; void main() { for (int i = 1; i <= 6; i++) { print('$i is ${oddOrEven(i)}'); } }

Output:

1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even

Example 3: Display Name

dart
String getDisplayName(String? firstName, String? lastName) { String first = firstName ?? 'Unknown'; String last = lastName ?? ''; return last.isNotEmpty ? '$first $last' : first; } void main() { print(getDisplayName('Alice', 'Smith')); // Alice Smith print(getDisplayName('Bob', null)); // Bob print(getDisplayName(null, null)); // Unknown }

Example 4: Absolute Value

dart
int absolute(int n) => n < 0 ? -n : n; void main() { print(absolute(-42)); // 42 print(absolute(15)); // 15 print(absolute(0)); // 0 }

🔹 Quick Reference: Conditional Operators in Dart

OperatorSyntaxPurpose
Ternarycond ? a : bChoose between two values
Null-coalescea ?? bUse b if a is null
Null-aware assigna ??= bAssign b to a only if a is null
Null-aware accessa?.propertyAccess property only if a is not null

Summary

  • The ternary operator condition ? trueValue : falseValue is a concise alternative to simple if-else assignments.
  • Use it for single-expression decisions — avoid it when logic is complex or multi-step.
  • Avoid nesting ternaries; switch to if-else if or switch expressions for multiple branches.
  • In null safety, prefer ?? over value != null ? value : fallback for cleaner code.
  • Ternary is especially powerful inside Flutter widget trees where everything is an expression.

In the next lesson, we'll explore one of Dart's most unique features: collection if and collection for operators!

WhatsApp