본문 바로가기
Project/모면

[Flutter] Future와 async/await

by 독서왕뼝아리 2023. 3. 19.

Future 클래스란 크게 두 가지 상태를 갖고 있다. 완료와 미완료 상태. 완료됐을 때 두 가지 결과를 기대한다. 바로 'data'와 'error' 이다.

Future<int> future = futureNumber();

future.then((val) {
// int가 나오면 해당 값을 출력
print('val: $val');
}).catchError((error) {
// error가 해당 에러를 출력
print('error: $error');
});

위처럼 then과 catchError 메서드를 이용해  결과의 분기를 구분한다.

 


 

async, await는 대표적인 비동기 관련 키워드이다. 

 

async는 함수를 비동기 함수로 만들어 준다. await를 사용하면 비동기 함수가 끝날 때까지 기다리고, 사용하지 않으면 기다리지 않는다.

void main() {
  printOne();
  printTwo();
  printThree();
}

printOne() {
  print("One");
}

printTwo() async {
  Future.delayed(Duration(seconds: 1), () {
    print("Future");
  });
  print("Two");
}

printThree() {
  print("Three");
}

One, Two, Three가 출력된 후 Future가 1초 후 출력된다.

 

 

void main() {
  printOne();
  printTwo();
  printThree();
}

printOne() {
  print("One");
}

printTwo() async {
  await Future.delayed(Duration(seconds: 1), () {
    print("Future");
  });
  print("Two");
}

printThree() {
  print("Three");
}

One, Three가 출력된 후 1초 후 Future, Two 순서대로 출력된다.

 

 

**

Dart 공식 문서에서는 Future 클래스 사용보다 await + try-catch 문을 사용하는 것을 권장한다.