Vòng lặp for trong Dart
🎯 Mục tiêu: Các loại vòng lặp for trong Dart.
💡 for cổ điển
for (int i = 0; i < 5; i++) {
print(i); // 0, 1, 2, 3, 4
}📝 for-in (Duyệt collection)
var fruits = ['Apple', 'Banana', 'Orange'];
for (var fruit in fruits) {
print(fruit);
}🔧 forEach (Functional)
fruits.forEach((fruit) {
print(fruit);
});
// Arrow syntax
fruits.forEach((f) => print(f));🎯 Với index
for (int i = 0; i < fruits.length; i++) {
print("$i: ${fruits[i]}");
}
// Hoặc với asMap
fruits.asMap().forEach((index, fruit) {
print("$index: $fruit");
});📱 Trong Flutter (hiếm dùng trực tiếp)
// Thường dùng trong build
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text(items[index]));
},
);✅ Checklist
- Dùng
for (;;)khi cần index control - Dùng
for-inđể duyệt collections - Dùng
forEachcho functional style
Last updated on