What is the best way to check if an Iterable is null in a 'for-in' loop? In a forEach loop, you could simply do this:
people?.forEach((person) {
print(person.name);
});
The ?.
will make sure that the loop only runs if people
isn't null. Is it possible to do that in a nice way in a 'for-in' loop as well? Or do you need to do something like this:
if (people != null) {
for (person in people) {
print(person.name);
}
}
Note that I'm only using print as an example, the actual work done in the loops would be more complicated and that I want to avoid forEach loops completely.
It seems like there should be a better way, but I can't find any good examples of that.
Maybe a method reference in the .forEach() will do the trick for you?
void main() {
people?.forEach(expensiveFuction);
}
void expensiveFuction(Person p) {
print(p.name);
}
EDIT: Another solution might be to provide an empty list, if people is null:
for (var p in people ?? []) {
print(p.name);
}
If people evaluates to null, the empty list will be used and no iteration will run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With