Reputation: 25
so when I tried without the print the code doesn't execute, but when the print is included the code runs 'normally', is there another way of coding this without using print?
Not Working
x.map((v) {
setState(() {
_userList.add(v.data['name']);
});
});
Working
print(x.map((v) {
setState(() {
_userList.add(v.data['name']);
});
}));
Upvotes: 0
Views: 215
Reputation: 5818
Assuming that x
is a List
, then this is expected behaviour. map
returns a lazy iterable. What this means is that nothing is actually executed until the mapped list is iterated. From the documentation:
This method returns a view of the mapped elements. As long as the returned Iterable is not iterated over, the supplied function f will not be invoked.
This is why it is working when you print - the print function needs to iterate over the items, and so setState is called.
The map
method is usually used to transform each item in a list in some way. If you want to execute something for each item in the list, consider using the forEach
method instead:
x.forEach((v) {
setState(() {
_userList.add(v.data['name']);
});
});
Upvotes: 2