Identify if a 2D list contains a list in Dart/Flutter

2,360

By default, dart compares high-level objects with references, but you need value based comparison because collection are high-level objects. collection package has equality methods for that case. Example:

import 'package:collection/collection.dart';

void main() async {
  final element = [1, 2];
  final b = [
    [1, 2] // equal values with element but not referenced
  ];
  final c = [element];

  print(b.contains(element)); // prints false
  print(c.contains(element)); // prints true

  for (final e in b) {
    print(ListEquality().equals(e, element)); // prints true
  }
}

Edit: The solution up above, now, is useful for Dart-only applications. If you are developing a Flutter application, it got couple of new methods:

listEquals for Lists: https://api.flutter.dev/flutter/foundation/listEquals.html

mapEquals for Maps: https://api.flutter.dev/flutter/foundation/mapEquals.html

setEquals for Sets: https://api.flutter.dev/flutter/foundation/setEquals.html

So, in our example, solution is:

import 'package:flutter/foundation.dart';

print(b.any((e) => listEquals(e, element))); // prints true
Share:
2,360
Srikanth Varma
Author by

Srikanth Varma

Updated on December 11, 2022

Comments

  • Srikanth Varma
    Srikanth Varma over 1 year

    How do I identify if a 2D list contains another list without using nested for-loops?

    I am looking for a method similar to in in python. I tried using list.contains(x), but it doesn't seem to identify lists:

    List a = [[1,2],[1,1],[2,2]];
    List b = [1,2];
    int c = 1;
    
    b.contains(c)    // returns true
    a.contains(b)    // returns false