1. fetch해온 데이터를 build화면까지 보여주자
- api_service.dart
여기서 static을 사용하는 이유는, 클래스 선언 없이 바로 프로퍼티나 메소드를 호출 할 수 있다.
ex) static이 없다면 ApiService().getTodaysToons() 이렇게 ApiService클래스를 선언한 후, 메소드에 접근.
하지만 있으니, ApiService.getTodaysToons(); 이렇게 바로 메소드에 접근 가능.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:toonflix/models/webtoon_model.dart';
class ApiService {
static const String baseUrl =
static const String today = "today";
static 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 webtoons = jsonDecode(response.body);
for (var webtoon in webtoons) {
final instance = WebtoonModel.fromJson(webtoon);
webtoonInstances.add(instance);
}
return webtoonInstances;
}
throw Error();
}
}
- home_screen.dart
print를 통해, api 데이터를 받아 온 것을 확인 할 수 있다. 하지만 이 과정이 너무 길고 복잡하다. 더 간단하게 하는 방법은
다음 내용에...
import 'package:flutter/material.dart';
import 'package:toonflix/models/webtoon_model.dart';
import 'package:toonflix/services/api_service.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<WebtoonModel> webtoons = [];
bool isLoading = true;
void waitForWebToons() async {
webtoons = await ApiService.getTodaysToons();
isLoading = false;
setState(() {});
}
@override
void initState() {
super.initState();
waitForWebToons();
}
@override
Widget build(BuildContext context) {
print(webtoons);
print(isLoading);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
centerTitle: true,
backgroundColor: Colors.white,
foregroundColor: Colors.green,
title: const Text(
"Today's 웹툰",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w400,
),
),
),
);
}
}
흐름 내용 정리
'코딩강의 > Flutter 로 웹툰 앱 만들기(플러터-노마드코더)' 카테고리의 다른 글
웹툰 만들기 - ListView (0) | 2023.08.03 |
---|---|
웹툰 만들기 - FutureBuilder (0) | 2023.08.03 |
웹툰 만들기 - fromJson (0) | 2023.08.01 |
웹툰 만들기 - AppBar & Data Fetching (0) | 2023.08.01 |
POMODORO APP 만들기 - Date Format (0) | 2023.07.31 |