Home > Blockchain >  How to check list of objects are equal?
How to check list of objects are equal?

Time:08-22

I have a student class

class Student{
  
  String? name;
  
  String? section;
  
  Student(this.name,this.section);
  
  @override
  bool operator == (Object other){
    return other is Student && other.name == name && other.section == section;
  }
  
  @override
  int get hashCode => name.hashCode & section.hashCode;
  
}

  List<Student> studentsOne = [
    Student("maverick","A"),
    Student("roger","A"),
    Student("kenny","B"),
    Student("kooper","A")
  ];
  
   List<Student> studentsTwo = [
    Student("maverick","A"),
    Student("roger","A"),
    Student("kenny","B"),
    Student("kooper","A")
  ];
  
  print(studentsOne == studentsTwo); // prints false

Any help would be nice. thanks in advance

CodePudding user response:

You can use package:collection/collection.dart

List<Student> studentsOne = [
  Student("maverick","A"),
  Student("roger","A"),
  Student("kenny","B"),
  Student("kooper","A")
];

List<Student> studentsTwo = [
  Student("maverick","A"),
  Student("roger","A"),
  Student("kenny","B"),
  Student("kooper","A")
];

if (const DeepCollectionEquality().equals(studentsOne, studentsTwo)) {
  print('studentsOne and studentsTwo are equal')
}

CodePudding user response:

using listEquals()

 List<Student> studentsOne = [
      Student("maverick","A"),
      Student("roger","A"),
      Student("kenny","B"),
      Student("kooper","A")
    ];

    List<Student> studentsTwo = [
      Student("maverick","A"),
      Student("roger","A"),
      Student("kenny","B"),
      Student("kooper","A")
    ];

listEquals(studentsOne, studentsTwo) //true

  • Related