LoginSignup
8
5

More than 5 years have passed since last update.

Future<dynamic>はFuture<XXX>にキャストできない

Posted at

DartではdynamicからStringやintなどの型へのキャストは自動的に行えるが、FutureからFutureやFutureなどへのキャストはエラーになる。

main(List<String> args) async {
  print(await getBool());
}

Future<bool> getBool() {
  return getDynamic();
}

Future<dynamic> getDynamic() {
  return Future.value(true);
}

実行結果

Unhandled exception:
type 'Future<dynamic>' is not a subtype of type 'Future<bool>'

解決方法

Futureを取得する処理をawaitしてdynamicからの自動キャストとすると正しく処理できる。

void main(List<String> args) async {
  print(await getBool());
}

Future<bool> getBool() async {
  return await getDynamic();
}

Future<dynamic> getDynamic() {
  return Future.value(true);
}

実行結果

true
8
5
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
8
5