Using Equatable in Flutter

Handling Object Equality

Jaecheol Park
2 min readFeb 11, 2024

When developing with Flutter, you often encounter situations where you need to verify the equality of objects in relation to state management. One common solution to this challenge is using the Equatable package. In this article, I will explain what the Equatable package is and why it is used in Flutter development.

What is the Equatable Package?

Equatable is a package for Dart that facilitates easy equality checks between objects. By default, Dart allows object equality to be checked using the == operator, which is based on object identity. That means it returns true only if two objects are the same instance. This poses a problem for value-based equality checks. Equatable allows for easy comparison based on the properties of objects, which is particularly useful in Flutter for state management.

Why Use Equatable?

  1. Efficiency in State Management: State management is a crucial concept in Flutter. Widgets need to be appropriately rebuilt whenever the state changes. Using Equatable, complex objects can be easily compared to accurately detect changes in state, allowing for widget rebuilding only when necessary. This helps optimize the performance of the app.
  2. Simplicity in Code: To manually implement object equality, you would need to override the hashcode and == operators. This can be repetitive and prone to errors. With Equatable, the package handles this implementation, so developers only need to specify the properties of the model. This makes the code more concise and easier to manage.
  3. Reduction in Bugs: Using Equatable can prevent mistakes or omissions that may occur during equality comparison. Since the package handles all comparison logic, consistent and reliable equality checks are possible, significantly reducing bugs in large and complex applications.

Example of Using Equatable

As a simple example, let’s look at how a user object could be implemented using Equatable.

import 'package:equatable/equatable.dart';

class Person extends Equatable {
const Person(this.name);

final String name;

@override
List<Object> get props => [name];
}

Here, props returns a list of properties that are used for object equality comparison. Equatable uses this list to determine if two objects are equal.

Conclusion

The Equatable package is a powerful tool in Flutter development for easily managing object equality. It enhances efficiency in state management, maintains code simplicity, and reduces the possibility of bugs. Therefore, using Equatable is highly recommended in the development of Flutter apps that require complex state management.

References

Equatable package link: https://pub.dev/packages/equatable

--

--