Toán tử ba ngôi (Ternary Operator) trong Dart
🎯 Mục tiêu: Viết conditional expression ngắn gọn.
💡 Cú pháp
condition ? valueIfTrue : valueIfFalse📝 Ví dụ
int age = 20;
String status = age >= 18 ? "Adult" : "Minor";
print(status); // Adult
// Trong string interpolation
print("Status: ${age >= 18 ? 'Adult' : 'Minor'}");📱 Trong Flutter
// Widget conditional
child: isLoading
? CircularProgressIndicator()
: Text("Loaded"),
// Color
color: isError ? Colors.red : Colors.green,
// Text
Text(count == 1 ? "1 item" : "$count items"),⚠️ Khi không nên dùng
// ❌ Quá phức tạp
var result = a ? (b ? "x" : (c ? "y" : "z")) : "w";
// ✅ Dùng if-else thay thế✅ Checklist
- Dùng
? :cho expressions đơn giản - Không lồng quá nhiều ternary
Last updated on