Dart convert every element of list

Gazihan Alankus picture Gazihan Alankus · Jun 1, 2016 · Viewed 7.3k times · Source

I have a List<String> stringValues; that are actually numbers in quotes. I want to convert this list to List<int> intValues. What's an elegant way to do this?

There is list.forEach() that does not return anything, there is iterable.expand() that returns an iterable per element, there is iterable.fold() that returns just one element for the whole list. I could not find something that will allow me to pass each element through a closure and return another list that has the return values of the closure.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jun 1, 2016

Use map() and toList() for this. toList() is necessary because map() returns only an Iterable:

stringValues.map((val) => int.parse(val)).toList()

or shorter (thanks to @AlexandreArdhuin)

stringValues.map(int.parse).toList()

Dartpad example