[flutter] async/await

동기화/비동기화

예시 #1

const oneSecond = Duration(seconds: 1);

Future<void> printWithDelay0(String message) async {
  await Future.delayed(oneSecond);
  print(message);
}
  
Future<void> printWithDelay1(String message) {
  Future.delayed(oneSecond)
  	.then((_) {
  		print(message);
  	});
}
  
void main() {
  printWithDelay0();
  for (int i = 0; i < 5; i++) {
  	print('hello ${i + 1}');
  }
  printWithDelay1();
}

결과 #1

hello 1
hello 2
hello 3
hello 4
hello 5
First time...
Second tine...

예시 #2

void main() async {
  await printWithDelay0();
  for (int i = 0; i < 5; i++) {
  	print('hello ${i + 1}');
  }
  await printWithDelay1();
}

결과 #2

First time...
hello 1
hello 2
hello 3
hello 4
hello 5
Second tine...

댓글

이 블로그의 인기 게시물

Next.js에서 자연스러운 Page Transition 방법

[flutter] Android - Package간 sdk version 등이 맞지 않아 오류가 발생하는 경우

[Windows] Chocolatey upgrade