본문 바로가기
ETC/Flutter

[flutter] Future 와 async를 사용해보자.

by 안주형 2021. 10. 17.

Future

  1. 다트에 의해서 future 객체가 내부적인 배열에 등록.
  2. Future 관련해서 실행되어야 하는 코드들이 이벤트 큐에 등록.
  3. 불완전한 future 객체가 반환.
  4. Synchronous(동기,순차적) 방식으로 실행되어야 할 코드 먼저 실행.
  5. 최종적으로 실제적인 data 값이 future 객체로 전달.
void main() {
  print('Before the Future');
  Future(() {
    print('Running the Future');
  }).then((_) {
    print('Future is complete');
  });
  print('After the Future');
}

위 소스의 출력결과는 아래와 같다.

Before the Future
After the Future
Running the Future
Future is complete

Async method

  1. 메서드를 통해서 나오는 결과물은 future
  2. Await 키워드를 만날때까지 Synchronous(동기,순차적) 방식으로 코드처리
  3. await 키워드를 만나면 future 가 완료될 때까지 대기
  4. future가 완료 되자마자 그 다음 코드들을 실행

No use async

String createOrderMessage() {
  var order = fetchUserOrder();
  return 'Your order is : $order';
}

Future<String> fetchUserOrder() {
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Large Latte',
  );
}

void main() {
  print('Fetching user order....');
  print(createOrderMessage());
}

위 소스의 출력 결과는 아래와 같다.

Fetching user order....
Your order is : Instance of 'Future<String>'

Use async

Future<String> createOrderMessage() async {
  print('synchronous');
  var order = await fetchUserOrder();
  return 'Your order is : $order';
}

Future<String> fetchUserOrder() {
  return Future.delayed(
    Duration(seconds: 2),
    () => 'Large Latte',
  );
}

void main() async {
  print('Fetching user order....');
  print(await createOrderMessage());
}

위 소스의 출력 결과는 아래와 같다.

Fetching user order....
synchronous
Your order is : Large Latte

연습

void main() async {
  methodA();
  await methodB();
  await methodC('main');
  methodD();
}

methodA() {
  print('A');
}

methodB() async {
  print('B start');
  await methodC('B');
  print('B end');
}

methodC(String from) async {
  print('C start from $from');

  Future(() { 
    print('C running Future from $from');
  }).then((_) {
    print('C end of Future from $from');
  });

  print('C end from $from');
}

methodD() {
  print('D');
}

위 코드의 실행 결과는 아래와 같다.

A
B start
C start from B
C end from B
B end
C start from main
C end from main
D
C running Future from B
C end of Future from B
C running Future from main
C end of Future from main

댓글