Webierta
Webierta

Reputation: 387

Dart: Check items in List of lists

Before adding a list I want to check that it does not exist so there are no repeated values. This works with a list of integers, but not with a list of other integer lists:

void main() {
  var listasN = List<int>();
  var n1 = 1;
  var n2 = 2;
  var n3 = 1;
  void addN(int n) {
    if (!listasN.contains(n)) {
      listasN.add(n);
    }
  }
  addN(n1);
  addN(n2);
  addN(n3);
  print(listasN);

  var listas = List<List<int>>();
  var lista1 = [1, 2, 3, 4];
  var lista2 = [5, 6, 7, 8];
  var lista3 = [1, 2, 3, 4];
  void addLista(List<int> ls) {
    if (!listas.contains(ls)) {
      listas.add(ls);
    }
  }
  addLista(lista1);
  addLista(lista2);
  addLista(lista3);
  print(listas);
}

Out:

[1, 2]
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]

The first function does not support repeated values, but the second does, why?

Upvotes: 1

Views: 507

Answers (1)

lrn
lrn

Reputation: 71613

Dart lists do not have an inherent equality. That is, the == operator only considers lists equal if it's the same list, not if it's different lists with the same content. That's generally how Dart handles equality of mutable types. The contains method uses equality for checking.

So, what you can do instead is to create a "list equals" method:

bool listEquals<T>(List<T> list1, List<T> list2) {
  if (list1.length != list2.length) return false;
  for (var i = 0; i < list1.length; i++) {
    if (list1[i] != list2[i]) return false;
  }
  return true;
}

Then you can check if a similar list is contained in your lists:

void addLista(List<int> ls) {
  if (!listas.any((ls2) => listEquals(ls, ls2))) {
    listas.add(ls);
  }
}

Upvotes: 3

Related Questions