Bỏ qua để đến nội dung

Toán tử ba ngôi (Ternary Operator)

🎯 Mục tiêu: Viết conditional expression ngắn gọn.


condition ? valueIfTrue : valueIfFalse

int age = 20;
String status = age >= 18 ? "Adult" : "Minor";
print(status); // Adult
// Trong string interpolation
print("Status: ${age >= 18 ? 'Adult' : 'Minor'}");

// Widget conditional
child: isLoading
? CircularProgressIndicator()
: Text("Loaded"),
// Color
color: isError ? Colors.red : Colors.green,
// Text
Text(count == 1 ? "1 item" : "$count items"),

// Quá phức tạp
var result = a ? (b ? "x" : (c ? "y" : "z")) : "w";
// Dùng if-else thay thế

  • Dùng ? : cho expressions đơn giản
  • Không lồng quá nhiều ternary