Skip to Content
Dart📘 Ngôn ngữ DartSwitch-Case Statement

Switch-Case trong Dart

1. Giới thiệu

switch-case giúp so sánh một biến với nhiều giá trị khác nhau, thay thế cho chuỗi if-else.

2. Cú pháp cơ bản

switch (variable) { case value1: // code break; case value2: // code break; default: // code mặc định }

3. Ví dụ với số

void main() { int day = 3; switch (day) { case 1: print('Thứ Hai'); break; case 2: print('Thứ Ba'); break; case 3: print('Thứ Tư'); break; default: print('Ngày khác'); } }

4. Ví dụ với String

void main() { String color = 'red'; switch (color) { case 'red': print('Màu đỏ'); break; case 'blue': print('Màu xanh'); break; case 'green': print('Màu lục'); break; default: print('Màu khác'); } }

5. Nhiều case cùng code

void main() { String day = 'Saturday'; switch (day) { case 'Saturday': case 'Sunday': print('Cuối tuần!'); break; case 'Monday': case 'Tuesday': case 'Wednesday': case 'Thursday': case 'Friday': print('Ngày làm việc'); break; } }

6. Switch Expression (Dart 3.0+)

void main() { String day = 'Monday'; String message = switch (day) { 'Monday' => 'Đầu tuần', 'Friday' => 'Cuối tuần làm việc', 'Saturday' || 'Sunday' => 'Nghỉ ngơi', _ => 'Giữa tuần', }; print(message); }

7. Pattern Matching (Dart 3.0+)

void main() { var value = (1, 'hello'); switch (value) { case (int n, String s) when n > 0: print('Số dương: $n, chuỗi: $s'); case (int n, String s): print('Số: $n, chuỗi: $s'); } }

8. So sánh với enum

enum Status { pending, approved, rejected } void main() { var status = Status.approved; switch (status) { case Status.pending: print('Đang chờ'); break; case Status.approved: print('Đã duyệt'); break; case Status.rejected: print('Từ chối'); break; } }

📝 Tóm tắt

  • switch-case thay thế nhiều if-else
  • Bắt buộc có break (trừ khi fall-through)
  • default xử lý các trường hợp còn lại
  • Dart 3.0+ hỗ trợ switch expression
  • Kết hợp tốt với enum
Last updated on