Skip to content

Instantly share code, notes, and snippets.

@hongsw
Created May 23, 2023 22:10
Show Gist options
  • Save hongsw/3195cd61e7ed0a90f8b630315f09442f to your computer and use it in GitHub Desktop.
Save hongsw/3195cd61e7ed0a90f8b630315f09442f to your computer and use it in GitHub Desktop.
crimson-patter-5991
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchPosts() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
// API 서버에서 데이터를 정상적으로 가져왔을 때
// JSON 문자열을 Dart 객체로 변환
List<dynamic> posts = json.decode(response.body);
for (var post in posts) {
print('Title: ${post["title"]}');
}
} else {
// API 서버에서 에러를 반환했을 때 에러 처리
throw Exception('Failed to load posts');
}
}
void main() async {
// Run fetchPosts
await fetchPosts();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment