LoginSignup
5
1

More than 5 years have passed since last update.

async関数の戻り値をコールバック関数内から返す

Last updated at Posted at 2018-10-15

async関数の戻り値をコールバック関数内から返す方法です。
といっても良くわからないと思うので、下のコードを見てください。
こんな感じで値を返したいときがあると思いますが、その方法の紹介記事です。

Future<String> hoge() async {
  fuga().then((){
    // ここからhoge関数の値を返したい
  })
  .catchError((){
    // ここからhoge関数の値を返したい
  });
}

Completerというクラスを使って次のようにかけます。

Future<String> hoge() async {
  final Comleter<String> completer;
  fuga().then((){
    completer.complete("then");
  })
  .catchError((){
    completer.completeError("error");
  });
  return completer.future;
}
5
1
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
5
1