0

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?

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
  • If what you need is only checking for the list equality you can follow this answer https://stackoverflow.com/a/22333042/8745788 – Mattia Aug 03 '19 at 08:55

1 Answers1

2

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;
  }
}
spenster
  • 548
  • 3
  • 9
  • 1
    Oh! what a minor mistake I have done, LOL, forget to mention function parameter type, this happens when you came from `JS`, thanks – ArifMustafa Aug 03 '19 at 02:11