50
18

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.

[Dart] type 'List<dynamic>' is not a subtype of type 'List<xxxx>' in type cast の対処方法

Last updated at Posted at 2020-01-08

jsonから読み込んだファイルを処理している時、次のようなエラーが出ることがあります。

final allSentences = widget.assets['sentences'];
final thisSentence =
        allSentences[widget.sentenceNo - 1] as Map<String, dynamic>;
// ↓ここでエラーが出る
final thisWordsNums = thisSentence['words'] as List<int>;
type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast

こうしたときは、 .cast<int>()でint型へキャストすることで、エラーを回避できます。

final allSentences = widget.assets['sentences'];
final thisSentence =
        allSentences[widget.sentenceNo - 1] as Map<String, dynamic>;
// .cast<int>()を追加
final thisWordsNums = thisSentence['words'].cast<int>() as List<int>;

int型でなく次のような場合も同様に.cast<Map<String, dynamic>>()で対処できます。

type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>' in type cast

参考

cast method - List class - dart:core library - Dart API
dart - type ‘List’ is not a subtype of type ‘List’ where - Stack Overflow

50
18
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
50
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?