Future 함수 정의

Future<String> myFuture() async{
    await Future.delayed(Duration(seconds: 2));
    return 'another Future completed';
}

FutureBuilder 소스코드 확인

FutureBuilder 인자값 확인 -> future, builder 정의 예정

builder메서드는 아래와 같이 context와 snapshot을 인자값으로 가지고 있음

snapshot은 특정 시점에 데이터를 복사해서 보관하는 것

snapshot이 복사해서 가지고 있는 future 데이터가 실제로 존재하는지 확인 필요

소스코드를 보면 builder는 AsyncSnapshot객체와 함께 제공되는데 이 객체는 connectionState에 3가지 중 한가지 속성을 가진다고 나와있음 → 없을때, 대기중일때 완료되었을때

future가 완료된 상태에서만 화면에 ui를 그릴수 있도록 조건식 생성, 데이터가 아직 도착하지 않았다면 대기중 표시

FutureBuilder(
    future: myFuture(),
    builder: (context, snapshot){
        // future가 완료된 상태일때
        if(snapshot.connectionState == ConnectionState.done){
            return Text(
                snapshot.data,
            );
        }
        // 완료된 상태가 아닐때 progress 출력
        return CircularProgressIndicator();
    }
)
728x90

+ Recent posts