How do I compare two objects to see if they are the same instance, in Dart?
For completeness, this is a supplemental answer to the existing answers.
If some class Foo
does not override ==
, then the default implementation is to return whether they are the same object. The documentation states:
The default behavior for all Objects is to return true if and only if this object and other are the same object.
You can use identical(this, other)
.
You're looking for "identical", which will check if 2 instances are the same.
identical(this, other);
A more detailed example?
class Person {
String ssn;
String name;
Person(this.ssn, this.name);
// Define that two persons are equal if their SSNs are equal
bool operator ==(Person other) {
return (other.ssn == ssn);
}
}
main() {
var bob = new Person('111', 'Bob');
var robert = new Person('111', 'Robert');
print(bob == robert); // true
print(identical(bob, robert)); // false, because these are two different instances
}