Reputation: 42556
I have below code in dart
:
List<Post> posts = postsData.map((post) =>
Post(
id: post['id'],
message: post['message']
).toList();
It runs map
on an array and return an array with the type Post
. But I got this error _TypeError (type 'List<dynamic>' is not a subtype of type 'List<Post>')
when executing the above code.
I can fix it by adding List<Post>.from
like below:
List<Post> posts = List<Post>.from(postsData.map((post) =>
Post(
id: post['id'],
message: post['message']
).toList());
I wonder is it the correct way to do that? Why doesn't toList
work for the generic type Post
? Why is it saying List<dynamic>
even I return Post
inside the map
loop?
Upvotes: 2
Views: 272
Reputation: 210
I found this solution:
List<Post> posts = postsData.map((post) =>
Post(
id: post['id'],
message: post['message']
).whereType<Post>().toList();
Upvotes: 0
Reputation: 15073
Its weird that I am not getting any _TypeError
.
You can try specify generic type on .map<Post>
List<Post> posts = postsData.map<Post>((post) =>
Post(
id: post['id'],
message: post['message']
)).toList();
Upvotes: 3