Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to null check in for-in loop?

Tags:

flutter

dart

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.

like image 511
Daniel Duvanå Avatar asked Dec 07 '22 11:12

Daniel Duvanå


1 Answers

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.

like image 166
Tidder Avatar answered Jan 14 '23 13:01

Tidder