Sobes.tech
Middle

Ako prepísať operáciu porovnania pre objekty vo Flutter?

sobes.tech AI

Odpoveď od AI

Na prepísanie operácií porovnania == a hashCode je potrebné ich implementovať v triede. Na to sa často používa balík 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];
}

Bez equatable by implementácia vyzerala takto:

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;
}

Pri prepísaní == je vždy povinné prepísať aj hashCode, aby sa zachoval kontrakt medzi nimi: ak sú dva objekty rovnaké podľa ==, ich hash kódy musia byť rovnaké. Opak nie je pravdivý.

Použitie:

final obj1 = MyObject(1, 'Test');
final obj2 = MyObject(1, 'Test');
final obj3 = MyObject(2, 'Iný');

print(obj1 == obj2); // Výstup: true
print(obj1 == obj3); // Výstup: false