Any Dart List Method that works this way?

class Word{
String word;
Word({required this.word});
}
List<Word> firstList = ["Add","All","Human","Moon","Free"];
List<Word> secondList= ["Add","Human","Free"];

If the element in the first list exists in the second list, I want it to return true, otherwise false.

Output that should be:

true
false
true
false
true

>Solution :

First, I’d make sure that Word can be compared easily:

class Word {
  String word;
  Word({required this.word});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is Word && other.word == word;
  }

  @override
  int get hashCode => word.hashCode;
}

Then you can do:

print(firstList.map((w) => secondList.contains(w)));

Check this DartPad for it

Leave a Reply