Simplify Equality Comparisons in Dart with Equatable

Feb 7, 2023 | Programming

Being able to compare objects in Dart can be a tedious task, mainly due to the need to override the == operator and hashCode. Fortunately, the Equatable package streamlines this process, allowing developers to focus on building features rather than dealing with boilerplate code.

Why Use Equatable?

The default behavior of Dart’s == operator is to return true only if two objects reference the same instance. This can lead to unexpected results when trying to compare instances of classes with the same properties. Without overriding == and hashCode, checking equality will not function as intended. Let’s consider the following scenario:

class Person {
  const Person(this.name);
  final String name;
}

void main() {
  final Person bob = Person('Bob');
  print(bob == Person('Bob')); // Output: false
}

In this analogy, imagine if every time you wanted to compare two apples, you had to check if they were the same apple rather than checking if they looked similar. This is the limitation in Dart’s default object comparison.

How to Use Equatable

To incorporate Equatable into your Dart project, follow these simple steps:

  • Add Equatable Dependency: Open your pubspec.yaml file and include the following line under dependencies:
  • dependencies:
      equatable: ^2.0.0
  • Install the Package: Run the following command:
  • # Dart
      dart pub get
      # Flutter
      flutter pub get
  • Extend Equatable: Modify your Person class to extend Equatable:
  • import 'package:equatable/equatable.dart';
    
    class Person extends Equatable {
      const Person(this.name);
      final String name;
    
      @override
      List get props => [name];
    }
      
    
    
    

    Now, comparing instances of Person becomes effortless:

    void main() {
      final Person bob = Person('Bob');
      print(bob == Person('Bob')); // Output: true
    }

    JSON Support

    If you’re working with JSON, Equatable easily integrates:

    class Person extends Equatable {
      const Person(this.name);
      final String name;
    
      @override
      List get props => [name];
    
      factory Person.fromJson(Map json) {
        return Person(json['name']);
      }
    }
    
    
    

    Troubleshooting

    If you encounter issues while implementing Equatable, consider the following:

    • Ensure that you have installed the dependencies correctly.
    • Check that all member variables in your class implementing Equatable are declared as final to maintain immutability.
    • If you face issues with equality checks, verify that your props are correctly overridden.

    For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

    Implementing toString

    You can customize the toString method in Equatable for debugging purposes. To include all props in your string representation, add the following:

    @override
    bool get stringify => true;

    This adds clarity by showing the properties when printing an instance of a class derived from Equatable.

    Recap: Equality Without Equatable vs. With Equatable

    Here’s a quick comparison:

    // Without Equatable
    class Person {
      const Person(this.name);
      final String name;
    
      @override
      bool operator ==(Object other) =>
          identical(this, other) ||
          other is Person &&
          runtimeType == other.runtimeType &&
          name == other.name;
    
      @override
      int get hashCode => name.hashCode;
    }
    
    // With Equatable
    import 'package:equatable/equatable.dart';
    
    class Person extends Equatable {
      const Person(this.name);
      final String name;
    
      @override
      List get props => [name];
    }
    
    
    

    Using EquatableMixin

    When it’s not feasible to extend Equatable due to existing class definitions, utilize the EquatableMixin:

    class EquatableDateTime extends DateTime with EquatableMixin {
      EquatableDateTime(int year, [int month = 1, int day = 1])
          : super(year, month, day);
    
      @override
      List get props => [year, month, day];
    }
    
    
    

    Conclusion

    Equatable simplifies object equality comparisons in Dart, enabling developers to write cleaner code without tedious boilerplate. By using Equatable, you can focus on your application’s logic, rather than getting bogged down by equality checks.

    At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

    Stay Informed with the Newest F(x) Insights and Blogs

    Tech News and Blog Highlights, Straight to Your Inbox