Flutter Equatable

Flutter Equatable:

In this tutorial, we are going to learn about Flutter equatable. Using flutter equatable we can Simplify Equality Comparisons. in order to compare different instances of the same class we have to override the == operator as well as hashcode. By default, ==  returns true if two objects are the same instance of the class.

Suppose, we have the following class named “person”:

class Person {
final String name;

const Person(this.name);
}

We can now create the instance of the above class by using the below code.

void main() {
final Person bob = Person("Bob");
}

Suppose, if we try to compare two instances of above person class either in our production code or in our tests we will run into a problem. as shown in below code.

print(bob == Person("Bob")); // false

In order to be able to compare two instances of person we need to change our class to override == and hashCode like so:

class Person {
final String name;

const Person(this.name);

@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Person &&
runtimeType == other.runtimeType &&
name == other.name;

@override
int get hashCode => name.hashCode;
}

Suppose, if we try to compare two instances of above person class either in our production code or in our tests we will get the below code as shown.

print(bob == Person("Bob")); // true

it will be able to compare different instances of the same classPerson.

You can see how this can quickly become a hassle when dealing with complex classes. This is where Equatable comes in.

What will Equatable do?

The Equatable, overrides both  == and hashCode for you so you don’t have to waste your time writing lots of boilerplate code.

There are other packages using which we can generate the boilerplate code. however, But we can run the code generation step which is not ideal for a developer.

With the help of Equatable, there is no need for code generation and we can focus more on writing amazing applications and less on mundane tasks.

Leave a Reply

Categories