본문 바로가기
Flutter

[Flutter] Fetch 간소화

by 김뱅쓰 2023. 5. 10.
List<WebtoonModel> webtoons = [];
  bool isLoading = true;

  void waitForWebToons() async {
    webtoons = await ApiService().getTodaysToons();
    isLoading = false;
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    waitForWebToons();
  }

fetch할때 stateful 함수를 써서 setstate함수쓰고 값들 모두 초기화하고 값들 각자 따로 변환해주고 불러올 필요없이

 

stateless 함수를 쓰고도 쉽게 간략화 할 수 있다.

Future<List<WebtoonModel>> webtoos = ApiService().getTodaysToons();
body: FutureBuilder(
        future: webtoons,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return const Text('There is data');
          }
          return const Text('Loading...');
        },
      ),

FutureBuilder를 쓰면 await async를 쓰지 않고도 값을 불러올 수 있다.