flutter(플러터) - 15-1. 비동기 예제

JungSik Heo·2026년 5월 10일

flutter

목록 보기
21/23

Flutter + JSONPlaceholder + ListView.builder 예제

# pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  http: ^1.2.1

main.dart

import 'dart:convert';

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

void main() {
  runApp(const MyApp());
}

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

  
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const PostPage(),
    );
  }
}

class PostPage extends StatefulWidget {
  const PostPage({super.key});

  
  State<PostPage> createState() => _PostPageState();
}

class _PostPageState extends State<PostPage> {
  // 📌 게시글 리스트 저장
  List posts = [];

  // 📌 로딩 상태
  bool isLoading = true;

  
  void initState() {
    super.initState();

    fetchPosts();
  }

  // =====================================================
  // API 요청
  // =====================================================

  Future<void> fetchPosts() async {
    final response = await http.get(
      Uri.parse(
        'https://jsonplaceholder.typicode.com/posts',
      ),
    );

    final data = jsonDecode(response.body);

    setState(() {
      posts = data;
      isLoading = false;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JSONPlaceholder ListView'),
      ),

      // =====================================================
      // BODY
      // =====================================================

      body: isLoading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: posts.length,
              itemBuilder: (context, index) {
                final post = posts[index];

                return Card(
                  margin: const EdgeInsets.all(10),
                  child: ListTile(
                    leading: CircleAvatar(
                      child: Text(
                        '${post['id']}',
                      ),
                    ),
                    title: Text(post['title']),
                    subtitle: Text(post['body']),
                  ),
                );
              },
            ),
    );
  }
}

API 주소

https://jsonplaceholder.typicode.com/posts
  • 무료 테스트용 JSON API
  • 게시글 데이터 제공

JSON 데이터 형태

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

코드 핵심 설명


1️⃣ http.get()

final response = await http.get(...)
  • 인터넷 요청
  • 서버 데이터 가져오기

2️⃣ jsonDecode()

final data = jsonDecode(response.body);
  • JSON 문자열 → Dart List 변환

3️⃣ setState()

setState(() {
  posts = data;
});
  • 화면 다시 그리기
  • ListView 업데이트

4️⃣ ListView.builder()

ListView.builder(...)
  • 많은 리스트를 효율적으로 생성
  • 필요한 화면만 렌더링

5️⃣ ListTile()

ListTile(...)
  • Flutter 기본 리스트 UI
  • title / subtitle 제공

실행 흐름

앱 시작
↓
fetchPosts()
↓
http.get()
↓
서버 응답
↓
jsonDecode()
↓
posts 저장
↓
setState()
↓
ListView 화면 갱신

실행 화면 느낌

[1] 게시글 제목
    게시글 내용

[2] 게시글 제목
    게시글 내용

최종 핵심 한 줄

Flutter에서는
http.get()으로 JSON 데이터를 받아와
ListView.builder로 화면에 출력한다.
profile
쿵스보이(얼짱뮤지션)

0개의 댓글