Home > Mobile >  Dart Object Comparison. Flutter
Dart Object Comparison. Flutter

Time:10-21

I am trying to compare objects, but the case is that although I have the following:

Person p = Person("nombre", "Apellido");
Person p2 = Person("nombre", "Apellido");
if(p == p2){
 print("IGUALES");
}else{
 print("DIFERENTES");
}

It keeps telling me that they are not the same when they are not, and I do not know why it happens or if the comparator "==" does not work when comparing objects. I have also tried but there is no way.

if(identical(p, p2)){
 print("IGUALES");
}else{
 print("DIFERENTES");
}

CodePudding user response:

This happens because by default the == operator checks if the object is the same object by checking it's reference in memory. If you want a value based equality you should either override the == operator and hashCode (which is difficult to do by hand) or you could use Equatable (a well known and maintained package for value based equality).

class Person extends Equatable {
  final String nombre;
  final String apellido;
  ...
  ...
  @override
  List<Object?> get props => [nombre, apellido];

}
  • Related