Skip to Content
Dart📘 Ngôn ngữ DartVòng lặp while và do-while

Vòng lặp while và do-while trong Dart

1. While loop

var count = 1; while (count <= 5) { print(count); count++; } // Output: 1, 2, 3, 4, 5

2. Do-while loop

var count = 1; do { print(count); count++; } while (count <= 5); // Chạy ít nhất 1 lần var x = 10; do { print(x); // In ra 10 } while (x < 5); // false nhưng vẫn chạy 1 lần

3. Infinite loop

var count = 0; while (true) { print(count); count++; if (count >= 5) break; }

4. Ví dụ thực tế: Menu

import 'dart:io'; void main() { var choice; do { print(''' === MENU === 1. Start 2. Settings 3. Exit Choose: '''); choice = int.tryParse(stdin.readLineSync() ?? '0') ?? 0; switch (choice) { case 1: print('Starting...'); break; case 2: print('Settings...'); break; case 3: print('Goodbye!'); break; default: print('Invalid choice'); } } while (choice != 3); }

📝 Tóm tắt

  • while - Kiểm tra trước khi chạy
  • do-while - Chạy ít nhất 1 lần
  • while (true) - Infinite loop
  • Dùng break để thoát
Last updated on