I have learned that what is the Equatable and how can I use it. But I just wonder that why should I use it?
I have found some reasons. One of them, when we wants to compare 2 or more same object from any class, it will use. they aren't same even if they properties same because of hash code. But equatable compares each other without hash code.
But I really wonder that where I will use in real life scenario?
Many Thanks..
CodePudding user response:
The overview section describes well
By default, == returns true if two objects are the same instance.
class Bar {
final int a = 2;
}
print(Bar() == Bar()); //false
While you like to judge instance/objects by its fields, we can use Equatable. A common use case when we like to update state(Check Bloc state-management)
class Foo extends Equatable {
final int a = 2;
@override
List<Object?> get props => [a];
}
print(Foo() == Foo()); //true
CodePudding user response:
By default 2 reference objects compare by references this means if you will create two equal objects and try to compare they will be different because references are different and you have manually check each field with each field of another object. For detailed information on equals
and hasCode
concept, you can read here.
As a result, if the object doesn't have specific equals
and hashCode
then you can't use such objects in the Set
, Map
, HashTables
and other data structures.
Another real example of this is unit tests. It will be very exhausting for you to write tests where you have to compare actual result with expected ones because on each test you have to compare each field instead of just using the equivalency
operator(==).
Remember, this is not a dart
feature this is a standard approach in computer science and data structures.
CodePudding user response:
Lets assume we have this user
class model:
class User extends Equatable {
final String fullName;
final int phone;
const User({
required this.fullName,
required this.phone,
});
@override
List<Object?> get props => [fullName, phone];
}
and we have these variable:
var myUser = User(fullName: 'Amir', phone: 123456);
List<User> users = [
User(fullName: 'Amir', phone: 123456),
User(fullName: 'Amir 2', phone: 5353453),
User(fullName: 'Amir 3', phone: 78978978),
];
and now we want to search in our users
and if myUser
is in users list remove it:
users.remove(myUser);
if we don't use Equatable
on User
we could find it. but now we can.