Joey Yi Zhao
Joey Yi Zhao

Reputation: 42556

How can I convert a array.map().toList to a generic type?

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

Answers (2)

barry
barry

Reputation: 210

I found this solution:

List<Post> posts = postsData.map((post) =>
    Post(
        id: post['id'],
        message: post['message']
  ).whereType<Post>().toList();

Upvotes: 0

Crazy Lazy Cat
Crazy Lazy Cat

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

Related Questions