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..
3
Answers
Lets assume we have this
user
class model:and we have these variable:
and now we want to search in our
users
and ifmyUser
is in users list remove it:if we don’t use
Equatable
onUser
we could find it. but now we can.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
andhasCode
concept, you can read here.As a result, if the object doesn’t have specific
equals
andhashCode
then you can’t use such objects in theSet
,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.The overview section describes well
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)