18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter(Dart)で複数の非同期処理を並行して待ちたい(Future.wait()の挙動)

Last updated at Posted at 2020-05-05

はじめに

Dartでは,dart:asyncFuture.wait()を使う事で複数の非同期処理を並行して待つことができます.
Flutterなどで,複数のAPIを同時に取得したい時に使えます.

動作確認

DartPadにコピー&ペーストで動作確認できます.

コード

void main() async {
  List<Future<bool>> futureList = [];
  for (int i = 0; i < 5; i++) {
    futureList.add(somethingAPI(i));
  }
  
  print('Future.wait() start');
  var futureWait = Future.wait(futureList);
  
  print('start await');
  var result = await futureWait;
  print(result);
  print('print end');
}

Future<bool> somethingAPI(int t) async {
  print(t.toString() + ' start');
  Future<bool> future =
      Future.delayed(Duration(seconds: t), () => t%2 == 0 ? true : false);

  bool value = await future;
  print(t.toString() + ' end');
  return value;
}

実行結果

0 start
1 start
2 start
3 start
4 start
Future.wait() start
start await
0 end
1 end
2 end
3 end
4 end
[true, false, true, false, true]
print end

説明

非同期処理のsomethingAPI(int t)は数秒後に値を返すAPIを想定した関数です.
Future.wait()にFutureインスタンスをListで渡す事で,そのすべてが完了するまでawaitで待つことができます.
非同期処理の実行結果はFuture.wait()の戻り値としてListで受け取ることができます.

上記のコードではFuture.wait()に対するawaitの挙動を確かめたかったので,futureWaitという変数を経由させました.しかし通常は直接awaitで受けても良いでしょう.

また,下記の様に.then().catchError()でチェインさせたりエラーハンドリングを行うことができます.

  var futureWait = Future.wait(futureList)
    .then(
      (content) {
        print('.then is called');
        return content;
      },
    ).catchError(
      (e) {
        // do something
        throw e;
      },
    );

Reference

Dart API reference documentation / wait method
解説 Dart 2 プログラミング言語 / 非同期処理-Future (Asynchronous Programming: Futures)
DartのFutureを使って非同期処理を書く

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?