Dart convert every element of list
11,605
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()
Related videos on Youtube
Author by
Gazihan Alankus
Flutter/Dart GDE, Assistant Professor, coder, wannabe entrepreneur.
Updated on June 07, 2022Comments
-
Gazihan Alankus almost 2 years
I have a
List<String> stringValues;
that are actually numbers in quotes. I want to convert this list toList<int> intValues
. What's an elegant way to do this?There is
list.forEach()
that does not return anything, there isiterable.expand()
that returns an iterable per element, there isiterable.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. -
Alexandre Ardhuin almost 8 yearsYou can also use
stringValues.map(int.parse).toList()
as shorthand. -
Günter Zöchbauer almost 8 yearsI always for get to do this. Thanks for the hint.