Enum equalization with other classes

Issue

I’ve created a class that only takes Enums as parameters. I figured I could create a third Enum where I would manually put every option so they have a better naming.

The only thing is, I can’t test if both my third Enum instance and my class instance with the same parameters are equal just by using the == operator. Tried using equatable and considering the Enum instance as my class instance since it does implement it, but nothing works. Of course, I could create a test where all my given parameters are equal, but I just wondered whether I could do something so they return true when using the == operator.

E.g.:

Configuration

enum A {
  a,
  b;
}
enum B {
  c,
  d;
}

class Class with EquatableMixin {
  const EveryDayOfYear({required this.aValue, required this.bValue});

  final A aValue;
  final B bValue;
  
  @override
  List<Object?> get props => [aValue, bValue];
}

enum C {
  ac(Class(aValue: A.a, bValue: B.c)),
  ad(Class(aValue: A.a, bValue: B.d)),
  bc(Class(aValue: A.b, bValue: B.c)),
  bd(Class(aValue: A.b, bValue: B.d));

  const C(this._handler);

  final Class _handler;

  @override
  A get aValue => _handler.aValue;

  @override
  B get bValue => _handler.bValue;

  @override
  List<Object?> get props => [aValue, bValue];
}

Objective

final instance = Class(aValue: A.a, bValue: B.c);
instance == C.ac; // I would like something so this operation returns true.

Solution

As commented by @Levi-Lesches here the answer to my problem was to override my operator ==:

  @override
  // ignore: hash_and_equals, already implemented by EquatableMixin
  bool operator ==(Object other) {
    return (super == other) ||
        ((other is Class) &&
            (week == other.aValue) &&
            (day == other.bValue));
  }

This solved my problem and is fair since my class instance is not an Enum, but my enum constant is actually my class instance.

Answered By – Felipe Morschel

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *