Created with <3 with dartpad.dev.
Last active
May 24, 2023 04:34
-
-
Save hongsw/d0721c02a1d7fe74feeca2ee7101d6d0 to your computer and use it in GitHub Desktop.
guardianapis 이용 예시
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://content.guardianapis.com/search?show-fields=thumbnail&q=food%20korean&api-key=test')); | |
if (response.statusCode == 200) { | |
// API 서버에서 데이터를 정상적으로 가져왔을 때 | |
// JSON 문자열을 Dart 객체로 변환 | |
var root = json.decode(response.body); | |
print(root["response"]); | |
List<dynamic> newslist = root["response"]["results"]; | |
for (var news in newslist) { | |
print('Title: ${news["webTitle"]}'); | |
} | |
} else { | |
// API 서버에서 에러를 반환했을 때 에러 처리 | |
throw Exception('Failed to load news'); | |
} | |
} | |
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