Created with <3 with dartpad.dev.
Created
May 23, 2023 22:10
-
-
Save hongsw/3195cd61e7ed0a90f8b630315f09442f to your computer and use it in GitHub Desktop.
crimson-patter-5991
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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