skip to Main Content

Recently was working with dart multi-dimensional list, i have tried to remove a row(list) from a 2 dimensional list but the remove has no effect neither contains method has a match.

 List<List<int>> list = [[1, 2], [3, 4]];
 print(list.contains([1,2])); // prints false also removing will not has an effect

while

 List<List<int>> list = [[1, 2], [3, 4]];
 print(list.contains(list[0])); // prints true and successful remove

Why passing a list doesn’t have a match, I know that comparison here is based on reference not the value, but shouldn’t lists be canonicalized just like String and other numerical data types.

2

Answers


  1. It seems correct,[1,2] != list[0].
    you can see the implement of the contains function:

     bool contains(Object? element) {
        for (E e in this) {
          if (e == element) return true;
        }
        return false;
      }
    

    In your case,you can use listEquals such as :

    list.retainWhere((item) => !listEquals(item, [1, 2]));
    
    Login or Signup to reply.
  2. You can use listEqual() to compare list

    var list = [
      [1, 2],
      [3, 4]
    ];
    list.removeWhere(
      (element) {
        return listEquals(element, [1, 2]);
      },
    );
    

    Output

    [log]  [[3, 4]]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search