반응형

네트워크를 통한 데이터를 가져오기, DB 쓰기 및 읽기, 파일 데이터 읽기 및 쓰기 등과 같은 경우 비동기 작업이 필요하다.

Future 란?
Future 클래스의 인스턴스이고, 비동기 작업의 결과를 나타내며 Uncompleted 또는 Completed의 두 가지 상태를 가질 수 있다.

Completed 상태는 작업이 완료된 상태이다. Uncompleted 상태는 작업이 완료되지 못한 상태이며, 완료할 작업은 event queue에 적재한다. 

Future는 보통 async, await와 함께 사용되며, 아래와 같이 사용한다.

  • async 함수를 정의하려면 함수 본문 앞에 async를 추가한다.
  • await 키워드는 비동기 함수에서만 작동한다.

1. Future, async, await
Future<void> printOrderMessage() async {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
  print('Your order is: $order');
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex and slow.
  return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}

void main() async {
  countSeconds(4);
  await printOrderMessage();
}

void countSeconds(int s) {
  for (var i = 1; i <= s; i++) {
    Future.delayed(Duration(seconds: i), () => print(i));
  }
}
// Awaiting user order...
// 1
// 2
// 3
// 4
// Your order is: Large Latte
2. Error 다루기

비동기 함수에서 오류를 처리하려면 try-catch를 사용한다.

Future<void> printOrderMessage() async {
  try {
    print('Awaiting user order...');
    var order = await fetchUserOrder();
    print(order);
  } catch (err) {
    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      const Duration(seconds: 4),
      () => throw 'Cannot locate user order');
  return str;
}

void main() async {
  await printOrderMessage();
}
728x90
반응형

'Flutter > Dart' 카테고리의 다른 글

Dart Study #2 클래스, 상속  (0) 2022.08.04
Dart Study #1 기본 문법  (0) 2022.08.04

+ Recent posts