Devdit
 

Flutter วนลูป List ด้วย ListView

830

Flutter วนลูป List ด้วย ListView บทความนี้สอนวิธีการวนลูปเพื่อแสดงข้อมูลจากตัวแปร List ออกสู่หน้าจอ โดยใช้ ListView Widget ซึ่งจะแสดงข้อมูลในลักษณะ column หรือแถวแนวตั้ง สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Flutter วนลูป List ด้วย ListView

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    var color = ['red', 'green', 'blue'];

    return Scaffold(
        appBar: AppBar(
          title: const Text('My Example App'),
        ),
        body: ListView.separated(
          itemCount: color.length,
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: Text(color[index].toString())),
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return const Divider();
          },
        ));
  }
}

คำอธิบาย

จากตัวอย่างตัวแปร List คือ color มี 3 ข้อมูลคือ red, green และ blue จากนั้นใช้คำสั่ง List.separated เพื่อแสดงข้อมูล โดยกำหนดจำนวนข้อมูลใน List ด้วย itemCount พร้อมกับแสดงข้อมูลออกสู่หน้าจอภายใน itemBuilder และสร้างเส้นแบ่ง หรือเส้นคั่นแต่ละข้อมูลด้วย separatorBuilder และ Divider

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ