2

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.

kris
  • 11,868
  • 9
  • 88
  • 110

1 Answers1

3

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.

Baker
  • 24,730
  • 11
  • 100
  • 106
  • 1
    I was hoping for an easier way - but searching has not found one. And this certainly works. I'll add to the answer that for any `Map` or `List` properties, `DeepCollectionEquality().equals(o, this)` can be used (need to `import 'package:collection/collection.dart';`). – kris Oct 15 '21 at 03:27