Sobes.tech
Middle

Como substituir a operação de comparação para objetos no Flutter?

sobes.tech IA

Resposta da IA

Para sobrescrever as operações de comparação == e hashCode, é necessário implementá-las na classe. Para isso, muitas vezes é utilizado o pacote equatable.

import 'package:equatable/equatable.dart';

class MyObject extends Equatable {
  final int id;
  final String name;

  const MyObject(this.id, this.name);

  @override
  List<Object?> get props => [id, name];
}

Sem equatable, a implementação seria assim:

class MyObject {
  final int id;
  final String name;

  const MyObject(this.id, this.name);

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

    return other is MyObject &&
        other.id == id &&
        other.name == name;
  }

  @override
  int get hashCode => id.hashCode ^ name.hashCode;
}

Ao sobrescrever ==, é sempre obrigatório também sobrescrever hashCode para manter o contrato entre eles: se dois objetos são iguais segundo ==, seus códigos hash devem ser iguais. O inverso não é verdadeiro.

Uso:

final obj1 = MyObject(1, 'Teste');
final obj2 = MyObject(1, 'Teste');
final obj3 = MyObject(2, 'Outro');

print(obj1 == obj2); // Saída: true
print(obj1 == obj3); // Saída: false