코딩강의/Flutter 로 웹툰 앱 만들기(플러터-노마드코더)
웹툰 만들기 - fromJson
김마드
2023. 8. 1. 20:12
1. json 디코딩하고 하나씩 보여주기
json 데이터는 디코딩 과정을 거쳐주어야 한다.
- webtoon_model.dart
Webtoon json 결과 값에 대한 클래스 정의를 해준다.
class WebtoonModel {
final String title, thumb, id;
WebtoonModel.fromJson(Map<String, dynamic> json)
: title = json['title'],
thumb = json['thumb'],
id = json['id'];
}
- api_service.dart
response.body의 결과 값을 jsonDecode를 통해 디코드를 진행하고, 그 값을 List에 하나씩 넣어 준다.
그리고 Future 타입은 await해서 받아온 값이 미래의 값(미정) 일 떄 쓰인다.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:toonflix/models/webtoon_model.dart';
class ApiService {
final String today = "today";
Future<List<WebtoonModel>> getTodaysToons() async {
List<WebtoonModel> webtoonInstances = [];
final url = Uri.parse('$baseUrl/$today');
final response = await http.get(url);
if (response.statusCode == 200) {
final List<dynamic> webtoons = jsonDecode(response.body);
for (var webtoon in webtoons) {
webtoonInstances.add(WebtoonModel.fromJson(webtoon));
}
return webtoonInstances;
}
throw Error();
}
}
느낀점
JS에서 함수형으로만 구현을 하다가 여기서는, 클래스가 많이 나오고 낯설긴 한데, 이것도 금방 익숙해지겠지.