I use the following code to compare two Person
object using the overridden ==
operator:
class Person {
String ssn;
String name;
Person(this.ssn, this.name);
bool operator ==(Object other) {
return identical(this, other) ||
other is Person &&
ssn == other.ssn &&
name == other.name;
}
@override int get hashCode => (ssn + name).hashCode;
}
main() {
var bob = Person('111', 'Bob');
var robert = Person('123', 'Robert');
print(bob == robert); // false
}
However, as this code works perfectly with Person
objects, is there a way to write one ==
operator function that works for any two types to compare them to check if they are equal or not ?
identical()
fromdart:core
? api.dart.dev/stable/2.6.1/dart-core/identical.htmlPerson.operator ==
work if theother
object isn't aPerson
? Or are you asking how to avoid implementing anoperator ==
override for every class?package:equatable
to make it slightly less tedious, but otherwise there's no automatic way without code generation.