19

How to convert a list from one type to another without a for loop?

List <String> lstring = <String>["1", "2"];
List <int> lint = lstring.map(int.parse);

I get the error:

type 'MappedListIterable<String, int>' is not a subtype of type 'List<int>'

2 Answers 2

34

You need to add a toList() to the end of the second line.

List <String> lstring = <String>["1", "2"];
List <int> lint = lstring.map(int.parse).toList();

This will do it.

Sign up to request clarification or add additional context in comments.

1 Comment

Most Iterable operations are lazy and only executed when the result is actually iterated which toList() needs to do to create a new list.
7
final List<String> lstring = ["1", "2"];
final List<int> newList = lstring.map((e)=>int.parse(e)).toList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.