Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart convert every element of list

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.

like image 585
Gazihan Alankus Avatar asked Jun 01 '16 09:06

Gazihan Alankus


People also ask

How do you convert to a list in darts?

We can convert Dart List to Map in another way: forEach() method. var map2 = {}; list.

How do you add a string to a list in darts?

For adding elements to a List , we can use add , addAll , insert , or insertAll . Those methods return void and they mutate the List object.


1 Answers

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

like image 194
Günter Zöchbauer Avatar answered Sep 30 '22 06:09

Günter Zöchbauer