Home > Back-end >  Dart: I want to check if the contents of 2 Lists are the same
Dart: I want to check if the contents of 2 Lists are the same

Time:07-28

One List is a List<String>? and the other is a List<dynamic>

I'd prefer not to change these data types. I just want to check if the contents are the same.

If I have a List [1, 2, 3] and a List [1, 2, 3] the output of a bool should be true

If I have a List [1, 2, 3] and a List [1, 3, 2] the output of a bool should be true

If I have a List [1, 2, 4] and a List [1, 2, 3] the output of a bool should be false

CodePudding user response:

I will sort in this case and check equal like

final e1 = [1, 2, 3]..sort();
final e2 = [1, 3, 2]..sort();

print(e1.equals(e2)); //true

CodePudding user response:

void main() {
  List<int> a = [1, 2, 3];
  List<dynamic> b = [1, 3, 3];


  bool checkSame(List<dynamic> a, List<dynamic> b) {
     var same = true;
    if (a.length != b.length) {
      same = false;
    } else {
      a.forEach((element) {
        if (element.toString() != b[a.indexOf(element)].toString()) {
          same = false;
        }
      });
    }
    return same;
  }
  
  bool val = checkSame(a, b);
  
  print(val);
}

CodePudding user response:

I recommend to use collection package with 564 like on pub.dev. to compare lists/maps/sets

i found from here https://stackoverflow.com/a/63633370/12838877

To compare list of integer and list of dynamic

import 'package:collection/collection.dart';


List<int> a = [1,2,4,5,6];
List<dynamic> b = [1,2,4,5,6];

bool isEqual = DeepCollectionEquality().equals(a,b);

print(isEqual)  // result is true without any error
  • Related