ArifMustafa
ArifMustafa

Reputation: 4965

How to compare arrays in Dart?

I'm trying to compare two array values existence, but inside iterator the comparison every doesn't seem to work.

void main() {
  var array1 = [1, 2, 3, 4];
  var array2 = [2, 3, 4, 1];
  print("Arrays are equal: ${compareArrays(array1, array2)}");
}

bool compareArrays(array1, array2) {

  if (array1.length == array2.length) {
    return array1.every( (value) => array2.contains(value) );
  } else {
    return false;
  }

}

and so I'm getting below said error:

Uncaught exception: TypeError: Closure 'compareArrays_closure': type '(dynamic) => dynamic' is not a subtype of type '(int) => bool'

How could I iterate array through each values and whats wrong I'm doing above?

Upvotes: 0

Views: 2038

Answers (1)

spenster
spenster

Reputation: 538

The problem is that Dart can't infer exactly what types array1 and array2 are, so it doesn't know what the function contains should be. If you specify types for the function arguments, it will work as expected fine:

void main() {
  var array1 = [1, 2, 3, 4];
  var array2 = [2, 3, 4, 1];
  print("Arrays are equal: ${compareArrays(array1, array2)}");
}

bool compareArrays(List array1, List array2) {

  if (array1.length == array2.length) {
    return array1.every( (value) => array2.contains(value) );
  } else {
    return false;
  }
}

Upvotes: 2

Related Questions