Home > Enterprise >  Dart/Flutter : How to compare if 2 objects are equivalent without using Equatable
Dart/Flutter : How to compare if 2 objects are equivalent without using Equatable

Time:10-15

I want to test if 2 objects, 2 different instances of the same class, have all the same property values;
(ie. see if they are logically equivalent).

I don't want to just check for if they are the exact same object (like this).

And I don't wish to use the Equatable package, simply because I don't want to mark my properties as final.

What I want is essentially a simple deep comparison of all properties of 2 objects.

CodePudding user response:

I believe you need to override two methods in your class to perform a custom comparison.

  1. the == operator
  2. the hashCode getter

For example:

class MyObj {
  String name;
  
  MyObj(this.name);
  
  @override
  bool operator ==(Object o) {
    if (o is MyObj && o.runtimeType == runtimeType) {
      if (o.name == name) {
        return true;
      }
    }
    return false;
  }
  
  @override
  int get hashCode => name.hashCode;
}

Testing this:

void main() {
  MyObj objA = MyObj('billy');
  MyObj objB = MyObj('bob');
  MyObj objC = MyObj('billy');
  
  print('object A == object B? ${objA == objB}');
  print('object A == object C? ${objA == objC}');
 
}

Should produce:

object A == object B? false
object A == object C? true

For overriding hashCode for multiple properties, perhaps check out this discussion.

  • Related