Dev to webs {Coding…}

ร บทเรียนฟรีด้านการพัฒนาซอฟต์แวร์ ที่ครอบคลุมเนื้อหาหลากหลาย ตั้งแต่การเขียนโค้ดพื้นฐานไปจนถึงเทคนิคขั้นสูง

บทที่ 17: การแสดงผล JSON จาก API ด้วย ListView

🔖 หมวดบทเรียน: การดึงข้อมูล JSON และแสดงในรูปแบบรายการในแอป

📌 เหมาะสำหรับ: ผู้ที่ต้องการแสดงรายการที่ดึงจาก API เช่น ข่าว, รายชื่อ, สินค้า ฯลฯ

🎯 เป้าหมาย: เข้าใจการ map ข้อมูล JSON ให้เป็น widget list โดยใช้ ListView.builder

🧭 เกริ่นนำ

หลังจากที่เราเรียนรู้การเรียก API ด้วย http.get() แล้ว บทนี้จะต่อยอดด้วยการนำข้อมูล JSON ที่ได้มาแสดงในหน้าแอป โดยใช้ ListView.builder เพื่อแสดงรายการแบบเลื่อน และเรียนรู้วิธี map ข้อมูล JSON ให้อยู่ในรูปแบบที่ Flutter เข้าใจ

📥 ตัวอย่างข้อมูลจาก API

API: https://jsonplaceholder.typicode.com/posts

ข้อมูลที่ได้จะมีหลายรายการ เช่น:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati",
  "body": "quia et suscipit..."
}

🧪 ตัวอย่างโค้ดแอปเต็ม

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: JsonListPage());
  }
}

class JsonListPage extends StatefulWidget {
  @override
  _JsonListPageState createState() => _JsonListPageState();
}

class _JsonListPageState extends State<JsonListPage> {
  List posts = [];

  @override
  void initState() {
    super.initState();
    fetchPosts();
  }

  void fetchPosts() async {
    final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      setState(() {
        posts = data;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("รายการโพสต์จาก API")),
      body: posts.isEmpty
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final post = posts[index];
                return ListTile(
                  title: Text(post['title']),
                  subtitle: Text(post['body'], maxLines: 2, overflow: TextOverflow.ellipsis),
                );
              },
            ),
    );
  }
}

✅ สรุป

  • ใช้ ListView.builder เพื่อแสดงรายการจำนวนมาก
  • ดึงข้อมูลด้วย http.get() แล้ว jsonDecode ให้เป็น List
  • แสดงผลแต่ละรายการด้วย ListTile

ในบทถัดไป เราจะเรียนรู้การใช้ SharedPreferences เพื่อบันทึกข้อมูลแบบ local storage เช่น การจำค่าล็อกอินหรือธีมของผู้ใช้