반응형
예제
pubspec.yaml
dependencies:
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 StatefulWidget {
const MyApp({super.key});
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<Post> posts = [];
@override
void initState() {
super.initState();
fetchPosts();
}
Future<void> fetchPosts() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
final List<dynamic> jsonData = jsonDecode(response.body);
setState(() {
posts = jsonData.map((e) => Post.fromJson(e)).toList();
});
} else {
print('Failed to load posts: ${response.statusCode}');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('HTTP Example'),
),
body: ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
final post = posts[index];
return ListTile(
title: Text(post.title),
subtitle: Text(post.body),
);
},
),
),
);
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
화면
반응형
'Development > Flutter' 카테고리의 다른 글
[Flutter] 안드로이드 릴리즈 빌드하기(.aab) (0) | 2024.03.24 |
---|---|
[Flutter] 애드몹(Admob) 광고 넣기 (0) | 2024.03.18 |
[Flutter] TextField (0) | 2024.02.23 |
[Flutter] StatefulWidget (0) | 2024.02.23 |
[Flutter] LayoutBuilder (0) | 2024.02.23 |