8
6

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 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
6
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
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?