[Flutter/Dart] Future.delayed

Tyger·2022년 2월 10일
1

Future.delayed

Future란 flutter의 비동기 작업을 처리하는 방식이며, value가 생성되기 전인 미완료와 value가 생성된 완료 두 가지의 상태를 가지고 있다

Future.delayed는 duration을 통해서 value가 생성될 시간을 제어할 수 있다

실제 프로젝트에서 delayed는 주로 progress bar로 값을 받아올 때 10-15초 정도 delayed 후에도 value가 생성되지 않으면 '다시 시도'를 할 수 있게 하는 버튼을 띄울 때나 UI를 control하고 싶을 때 주로 사용하는 것 같고 비동기 처리는 거의 대부분 async-await를 사용한다

아래 코드는 generate로 생성된 index의 홀수를 먼저 출력하고 5초 뒤 짝수를 출력하는 delayed 방법이다
(index % 2 == 0) => index를 2로 나눈 몫이 0이면 짝수를 구분하는 로직이다

짝수를 출력하는 print가 먼저 출력 되어야 하지만 future.delayed 때문에 아래의 print가 먼저 출력 되는 것이다


void main(){
  List.generate(10, (int index){
    if(index % 2 == 0){
         Future.delayed(Duration(milliseconds : 5000),() {
    print(index);
  });
    }else{
      print(index);
    }
  });
}
profile
Flutter Developer

0개의 댓글