Sobes.tech
Middle

Kaip perrašyti palyginimo operaciją objektams Flutter?

sobes.tech AI

Atsakymas iš AI

Norint perrašyti lyginimo operacijas == ir hashCode, jas reikia įgyvendinti klasėje. Dažnai naudojamas paketą 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];
}

Be equatable, jų įgyvendinimas atrodo taip:

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

Perrašant ==, visada būtina perrašyti ir hashCode, kad būtų išlaikyta jų sutartis: jei du objektai yra lygūs pagal ==, jų hash kodai turi būti lygūs. Atvirkščiai, tai nėra teisinga.

Naudojimas:

final obj1 = MyObject(1, 'Testas');
final obj2 = MyObject(1, 'Testas');
final obj3 = MyObject(2, 'Kitas');

print(obj1 == obj2); // Išvestis: true
print(obj1 == obj3); // Išvestis: false