When I use for-in loop in Dart, which one should I use, and why?
List<int> numbers = [1, 2, 3, 4];
for (var number in numbers)for (final number in numbers)for (int number in numbers)for (final int number in numbers)- Or else?
When I use for-in loop in Dart, which one should I use, and why?
List<int> numbers = [1, 2, 3, 4];
for (var number in numbers)for (final number in numbers)for (int number in numbers)for (final int number in numbers)From the above options, all of them would work. But the cleaner way is to use
for(var number in numbers)
Why?
The var we declare is the data type which accepts every types, and become free of getting the DataType mismatch compile time error. It gives you more freedom on working with the variables of the List.
However, the other ones are more stringent towards a particular data type, in this case int.
I have followed some of the documentations, and there, var is the preferred way of using the for...in loop. Please see => dart for-in-loop
Add-ons
There is one more looping style in dart, and that is forEach(). Please note:
Note that this guideline specifically says “function literal”. If you want to invoke some already existing function on each element,
forEach()is fine.
List<int> numbers = [1, 2, 3, 4];
numbers.forEach((element){
print(element); // 1 2 3 4
});
// OR - thanks to Richard
numbers.forEach(print); // 1 2 3 4 5
According to the Effective Dart: Usage page, var number in numbers or final number in numbers is the most idiomatic way to iterate through items in a list.
In general, we should avoid the forEach method and allow Dart to infer the type where stating the type would be redundant to us, the editor and the software.