Flutter + JSONPlaceholder + ListView.builder 예제
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});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const PostPage(),
);
}
}
class PostPage extends StatefulWidget {
const PostPage({super.key});
@override
State<PostPage> createState() => _PostPageState();
}
class _PostPageState extends State<PostPage> {
List posts = [];
bool isLoading = true;
@override
void initState() {
super.initState();
fetchPosts();
}
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;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('JSONPlaceholder ListView'),
),
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);
3️⃣ setState()
setState(() {
posts = data;
});
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로 화면에 출력한다.