퓨처빌더

차준우·2024년 7월 5일

flutter

목록 보기
17/25

stateless에서 fetch하기

import 'package:flutter/material.dart';
import 'package:navertoon/models/webtoon_model.dart';
import 'package:navertoon/services/api_service.dart';

class HomeScreen extends StatelessWidget {
  HomeScreen({super.key});

  Future<List<WebtoonModel>> webtoons = ApiService.getTodaysToons();

  @override
  Widget build(BuildContext context) {
    print(webtoons);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("오늘의 웹툰",
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
            )),
        foregroundColor: Colors.green,
        backgroundColor: Colors.white,
        elevation: 2, // 음영
      ),
    );
  }
}

이렇게 코드를 바꿔보자. stateless로 변경하고 state관련 코드를 모두 지움

apiservice의 반환형태 Future를 출력해보자

값이 아니라 인스턴스가 반환된다

futurebuilder

 return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("오늘의 웹툰",
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w600,
            )),
        foregroundColor: Colors.green,
        backgroundColor: Colors.white,
        elevation: 2, // 음영
      ),
      body: FutureBuilder(
        future: webtoons, // await효과
        builder: (context, snapshot) {
          //snapshot으로 future의 상태를 알 수있다. 오류인지, 값을 받았는지
          if (snapshot.hasData) {
            return const Text("there is data!!");
          } else {
            return const Text("Lodaing");
          }
        },
      ),
    );

futurebuilder위젯의 속성들이 다음 효과를 낸 것이다

  • future : await(알아서 값을 기다림)
  • snapshot : state관리

FutureBuilder는 future값을 기다릴 수 있고, 데이터가 존재하는 지 알 수 있다.

profile
개애발

0개의 댓글