Both the Collection for-in and map() can return some manipulation of elements from a previous collection. Is there ever any reason to prefer using one over the other?
var myList = [1,2,3];
var alteredList1 = [for(int i in myList) i 2]; //[3,4,5]
var alteredList2 = myList.map((e) => e 2).toList(); //[3,4,5]
CodePudding user response:
Use whichever is easier and more readable. That's a deliberately vague answer, because it depends on what you are doing.
Any time you have something ending in .toList()
I'd at least consider making it into a list literal. If the body of the map
or where
is simple, you can usually rewrite it directly to a list literal using for
/in
(plus if
for where
).
And then, sometimes it gets complicated, you need to use the same variable twice, or the map
computation uses a while
loop, or something else doesn't just fit into the list literal syntax.
Then you can either keep the helper function and do [for (var e in something) helperFunction(e)]
or just do something.map((e) { body of helper function }).toList()
. In many cases the latter is then more readable.
So, consider using a list literal if your iterable code ends in toList
, but if the literal gets too convoluted, don't feel bad about using the .map(...).toList()
approach.
Readability is all that really matters.
CodePudding user response:
Not an expert but personally I prefer the first method. Some reasons:
- You can include other elements (independent from the for loop) in the same list:
var a = [1, 2, 3];
bool include5 = true;
var b = [
1,
for (var i in a) i 1,
if (include5) 5,
];
print(b); // [1, 2, 3, 4, 5]
- Sometimes when mapping models to a list of Widgets the
.map().toList()
method will produce aList<dynamic>
, implicit casting won't work. When you come across such an error just avoid the second method.