[flutter] FutureBuilder란?

곽준영·2023년 3월 3일
0

Future(비동기) 와의 상호 작용에 대한 최신 스냅샷을 기반으로 자체적으로 빌드되는 위젯

FutureBuilder

Expanded(
  child: Container(
    alignment: Alignment.topCenter,
    margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
    child: FutureBuilder<List<Info>>(
      future: info,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          // 정상적으로 데이터를 받을 경우
          return buildList(snapshot.data);
        } else if (snapshot.hasError) {
          // 에러가 발생한 경우
          print(snapshot.error);
          return Text("${snapshot.error}에러!!");
        }
        return Container();
      },
    ),
  ),
),

Widget buildList(snapshot) {}

전체 코드

class Info {
  final String seq;
  final String educ_name;
  final String image;
  final String cat;
  final String sub_cat;

  Info({
    required this.seq,
    required this.educ_name,
    required this.image,
    required this.cat,
    required this.sub_cat,
  });

  factory Info.fromJson(Map<String, dynamic> json) {
    return Info(
      seq: json["seq"],
      educ_name: json["educ_name"],
      image: json["image"],
      cat: json["cat"],
      sub_cat: json["sub_cat"],
    );
  }
}

late Future<List<Info>> info;


Expanded(
  child: Container(
    alignment: Alignment.topCenter,
    margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
    child: FutureBuilder<List<Info>>(
      future: info,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return buildList(snapshot.data);
        } else if (snapshot.hasError) {
          print(snapshot.error);
          return Text("${snapshot.error}에러!!");
        }
        return Container();
      },
    ),
  ),
),

Widget buildList(snapshot) {}
profile
I want to become a versatile freelancer programmer💻

0개의 댓글