1

I am trying to search a List to see if it contains another list, using .contains

However, it doesn't work.

void main() {
  List cake = [[true, 8728], [true, 3231], [true, 9981], [true, 4323], [true, 6456], [true, 3244], [true, 4355]];
  print(cake.contains([true, 9981])); // Prints false, although cake contains [true, 9981]
  List piece = [true, 9981];
  cake.remove(piece); // Does not remove [true, 9981] from the List cake
  print(cake); // List remains unaltered
}

I assume .contains and .remove can't search for or remove a List from a List? Am I doing something wrong? Otherwise, what's the best way to do what I'm trying to do, other than looping through the list?

Shahmil
  • 311
  • 1
  • 9

1 Answers1

1

Your problem is that List<E>.contains and List<E>.remove (among other List methods) use E.operator == to match the item, but your element type is List, and List.operator == checks only for object identity instead of performing a deep equality check. (That is, [1] == [1] is false because each instance of [1] is a separate List object.)

One way to do what you want is instead to use List.removeWhere with a deep List equality check.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204