Sobes.tech
Middle

Kako prepisati operaciju poređenja za objekte u Flutteru?

sobes.tech АИ

Одговор од АИ

Da biste prepisali operacije poređenja == i hashCode, potrebno je da ih implementirate u klasi. Za to se često koristi 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];
}

Bez equatable, implementacija bi izgledala ovako:

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

Prilikom prepisivanja ==, uvek je obavezno da prepišete i hashCode, kako biste sačuvali ugovor između njih: ako su dva objekta jednaka prema ==, njihovi hash kodovi moraju biti jednaki. Obrnuto nije tačno.

Upotreba:

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

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