FutureBuilder

샤워실의 바보·2023년 11월 13일
0
post-thumbnail
import 'package:flutter/material.dart';
import 'package:toonflix/models/webtoon_model.dart';
import 'package:toonflix/services/api_service.dart';

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

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

  
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 2,
        backgroundColor: Colors.white,
        foregroundColor: Colors.green,
        title: const Text(
          "어늘의 웹툰",
          style: TextStyle(
            fontSize: 24,
          ),
        ),
      ),
      body: FutureBuilder(
        future: webtoons,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return const Text("There is data!");
          }
          return const Text('Loading....');
        },
      ),
    );
  }
}

FutureBuilder는 Flutter에서 비동기 연산 (Future)의 결과에 따라 위젯을 구축하는 데 사용되는 위젯입니다. 이는 특히 네트워크 요청, 데이터베이스 조회 등 비동기 작업의 결과를 기반으로 UI를 표시하거나 업데이트할 때 유용합니다.

FutureBuilder의 기본 구조

FutureBuilder는 다음과 같은 주요 속성을 가집니다:

  1. future: Future 객체를 받습니다. 이 객체는 비동기 작업을 나타내며, 일반적으로 데이터를 가져오는 API 호출 등이 될 수 있습니다.
  2. builder: 이 함수는 Future의 결과에 따라 위젯을 만듭니다. 두 개의 매개변수를 받습니다:
    • BuildContext context: 현재 위젯의 컨텍스트입니다.
    • AsyncSnapshot snapshot: Future의 상태와 결과를 포함하는 객체입니다.

HomeScreen 클래스에서의 FutureBuilder 사용 예시

body: FutureBuilder(
  future: webtoons,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return const Text("There is data!");
    }
    return const Text('Loading....');
  },
),

이 코드에서 FutureBuilderwebtoons Future의 결과를 기반으로 위젯을 구성합니다. webtoonsApiService.getTodaysToons()의 결과를 담고 있으며, 이는 오늘의 웹툰 리스트를 비동기적으로 가져오는 작업입니다.

  • snapshot.hasData: 이 조건문은 Future가 데이터를 성공적으로 받아온 경우를 확인합니다. 데이터가 있으면, "There is data!"라는 텍스트를 표시하는 위젯을 반환합니다.
  • 데이터가 아직 도착하지 않았거나 로딩 중인 경우, "Loading...."라는 텍스트를 표시합니다. 이는 Future가 완료될 때까지 사용자에게 로딩 상태를 알리는 방법입니다.

FutureBuilder의 장점

  • 비동기 작업 처리의 간소화: FutureBuilder를 사용하면 비동기 작업의 결과에 따라 UI를 업데이트하는 로직을 위젯 내부에 직접 구현할 필요가 없습니다.
  • 상태 관리 용이: Future의 상태(로딩, 완료, 에러 등)에 따라 다른 위젯을 표시할 수 있습니다.
  • 코드의 가독성 향상: 비동기 작업과 UI 코드가 FutureBuilder를 통해 명확하게 구분됩니다.

FutureBuilder는 Flutter 앱에서 비동기 작업의 결과를 효율적으로 관리하고, 사용자에게 적절한 피드백을 제공하는 데 매우 유용한 위젯입니다.

profile
공부하는 개발자

0개의 댓글