Home > front end >  Check if two object are equal in dart
Check if two object are equal in dart

Time:06-08

I'm here with some doubts about the comparison of objects in dart. I have two lists with objects of the same type and when I compare them using contains it says that there are no equal objects, however, if I compare all the parameters it already says that there are equal objects. I don't understand why

  int checkIfMealDuplicated(List restrictedBookings, List bookings) {
    for (Meal restrictedBooking in restrictedBookings) {
      for (Meal booking in bookings) {
        if (restrictedBooking.data == booking.data &&
            restrictedBooking.especial == booking.especial &&
            restrictedBooking.local == booking.local &&
            restrictedBooking.tipo == booking.tipo) {
          return restrictedBookings.indexOf(restrictedBooking);
        }
      }
    }
    return -1;
  }

Is there any way to avoid doing all those if comparisons?

CodePudding user response:

In Dart, any Object has a bool operator ==(Object other) method, which can be overridden so that it compares individual properties (or based on whatever computations you see fit). If the method is not overridden, then equality is tested by reference, so two different objects will be evaluated as non-equal, even if they have the same values.

You can override the operator yourself - or you can use a solution like equatable.

Manually:

class Meal {
  // ...

  @override
  bool operator ==(Object other) {
    if (identical(this, other) { 
      return true; 
    }

    if (other.runtimeType != Meal) {
      return false;
    }
    
    return this.data == other.data &&
           this.especial == other.especial &&
           this.local == other.local &&
           this.tipo == other.tipo;
  }

  // When overriding the equality operator, it's also necessary
  // to override the hashCode getter.
  @override
  int get hashCode => hashAll([data, especial, local, tipo]);
}

Or using equatable:

class Meal extends Equatable {
  // ...
  
  @override
  List<Object> get props => [
    data,
    especial,
    local,
    tipo,
  ];
}

One more note: if any of the fields of Meal are also objects, you will need to do the same for those classes too.

  •  Tags:  
  • dart
  • Related