Home > Back-end >  Dart, the type int used in the for loop must implement iterable
Dart, the type int used in the for loop must implement iterable

Time:05-06

I want to use Dart for…in loop in this function but I keep facing this error even though I declared the arr as an Iterable<int>

function:

void sumOfTwoNumbers(int targetSum, Iterable<int>  arr) {
  for (int i in arr.length-1) {
//stuff
  }
}

It's working with a normal for loop though, I don't know how can I fix this, for any help that would be appreciated

CodePudding user response:

Because arr.length you are trying to iterate over a int

arr is of type Iterable which is expected on the statement:

for (var T element in Iterable<T>) { /* ... */ }

So:

void sumOfTwoNumbers(int targetSum, Iterable<int>  arr) {
  for (int i in arr) {
    //stuff
  }
}

Ignore the last element

And if you want to remove the last element, just create another list from your original list that takes only the first N - 1 elements, to do that you can use take from Iterable API:

Note: in this case if your array is empty the length will be zero which results in 0 - 1 -> -1 which throws a RangeError to avoid it you can use max() from dart:math API

void sumOfTwoNumbers(int targetSum, Iterable<int>  arr) {
  // Iterable over all elements except by the last one
  for (int i in arr.take(arr.length - 1)) {
    //stuff
  }
}

By using max():

import 'dart:math';

void sumOfTwoNumbers(int targetSum, Iterable<int>  arr) {
  // Iterable over all elements except by the last one
  for (int i in arr.take(max(arr.length - 1, 0))) {
    //stuff
  }
}

Skip the first element

Same rule applies if you want skip the first element, you can use the skip API either:

void sumOfTwoNumbers(int targetSum, Iterable<int>  arr) {
  // Iterable over all elements except by the first one by skipping it
  for (int i in arr.skip(1)) {
    //stuff
  }
}

Reference

Take a look at Dart codelabs/iterables it can help you understand better how collections, lists and iterables works in Dart.

  • Related