Ternary & Conditional Expressions
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:
dartcondition ? valueIfTrue : valueIfFalse
It reads like a question: "If condition is true, give me valueIfTrue; otherwise give me valueIfFalse."
dartvoid 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
| Situation | Prefer |
|---|---|
| Simple value assignment between two options | Ternary ? : |
| Complex logic with multiple statements per branch | if-else |
| Inline expressions in string interpolation | Ternary |
| Readability matters more than brevity | if-else |
| Conditions with side effects (print, API call) | if-else |
Good Use of Ternary
dartvoid 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
dartvoid 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:
dartvoid 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:
dartvoid 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 ??:
dartString 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:
dartWidget 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
dartint 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
dartString 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
dartString 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
dartint 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
| Operator | Syntax | Purpose |
|---|---|---|
| Ternary | cond ? a : b | Choose between two values |
| Null-coalesce | a ?? b | Use b if a is null |
| Null-aware assign | a ??= b | Assign b to a only if a is null |
| Null-aware access | a?.property | Access property only if a is not null |
Summary
- The ternary operator
condition ? trueValue : falseValueis a concise alternative to simpleif-elseassignments. - Use it for single-expression decisions — avoid it when logic is complex or multi-step.
- Avoid nesting ternaries; switch to
if-else iforswitchexpressions for multiple branches. - In null safety, prefer
??overvalue != null ? value : fallbackfor 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!