Sobes.tech
Middle

Kā pārrakstīt salīdzināšanas operāciju objektiem Flutter?

sobes.tech AI

Atbilde no AI

Lai pārrakstītu salīdzināšanas operācijas == un hashCode, tās ir jāievieš klasē. Bieži tiek izmantots pakotne 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, to realizācija izskatās šādi:

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

Pārrakstot ==, vienmēr ir obligāti pārrakstīt arī hashCode, lai saglabātu to līgumu: ja divi objekti ir vienādi pēc ==, to hash kodiem jābūt vienādiem. Pretējā gadījumā tas nav pareizi.

Izmantošana:

final obj1 = MyObject(1, 'Tests');
final obj2 = MyObject(1, 'Tests');
final obj3 = MyObject(2, 'Cits');

print(obj1 == obj2); // Izvade: true
print(obj1 == obj3); // Izvade: false