Dart の非同期処理/同期処理

thenを使用 (非同期処理)

void main(){
  print("A");
  futurePrint(Duration(milliseconds: 2000), "B")
    .then((status) => print(status));
  print("C");
  futurePrint(Duration(milliseconds: 1000), "D")
    .then((status) => print(status));
  print("E");
}

Future<String> futurePrint(Duration dr, String msg){
  return Future.delayed(dr).then((onValue) => msg);
}

//A
//C
//E
//D
//B

async / await を使用 (同期処理)

void main() async {
  print("A");
  await futurePrint(Duration(milliseconds: 2000), "B")
    .then((status) => print(status));
  print("C");
  await futurePrint(Duration(milliseconds: 1000), "D")
    .then((status) => print(status));
  print("E");
}

Future<String> futurePrint(Duration dr, String msg){
  return Future.delayed(dr).then((onValue) => msg);
}

//A
//B
//C
//D
//E
This entry was posted in Dart, Flutter, 技術情報. Bookmark the permalink.

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です