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.

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.