'Is there any difference when using map or for loop inside a list in Dart?
I wasn't able to find an answer to this. Hope any of you can explain if there is any difference beyond that one of them looks prettier.
Let's say I have a list of Strings (just an example, any list use case fits)
final strings = ['string 1', 'string 2', 'string 3'];
And I want to render those strings in some Text widgets.
Doing it with a for loop, like this:
Column(
children: [
for(final string in strings)
Text(string),
],
);
Or doing it with map, like this:
Column(
children: strings.map((String string) => Text(string)).toList()
);
Is there any difference in performance or something else?
Solution 1:[1]
In this specific case it won't change the end result.
However some functions on list, map included return a lazy Iterator. Which means that any computation that happens before the toList() will be made only on the necessary items.
In other words if you have a list of 100 elements and call myList.map(mappingFn).take(5).toList() the mapping function will be called only 5 times.
For example:
void main() {
// mappingFn will be called 2 times
[1,2,3,4,5].map(mappingFn).take(2).toList();
}
String mappingFn(int n) {
print('called $n');
return n.toString();
}
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ced |
| Solution 2 | Sumit Kumar |

