2

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if I want to minus 1 from the list? like for (int i in arr-1) it keep giving an error
@YassineBENNKHAY I updated my answer hope it can answer your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.