Dart Równość i Pakiet Equatable

Równość służy do sprawdzania, czy dwa obiekty są równe, czy nie, za pomocą ==
operatora. Jeśli dwa obiekty są równe ==
, operator ocenia na, w true
przeciwnym razie ocenia na false
.
W Dart domyślnie ==
operator sprawdza równość referencyjną i ocenia, true
kiedy dwa obiekty są tą samą instancją lub należą do tego samego odniesienia. Jeśli porównamy dwa niestałe obiekty, które mają te same wartości, to ocenia się na false
.
- Stwórzmy
User
klasę:
class User {
final String? name;
final int? age;
const User({this.name, this.age});
}
void main() {
User user = User(name: "Usama", age: 10);
User administrator = User(name: "Usama", age: 10);
print(user == administrator);
}
void main() {
User user = const User(name: "Usama", age: 10);
User administrator = const User(name: "Usama", age: 10);
print(user == administrator);
}
4. Ale co, jeśli chcemy porównać dwa niestałe obiekty według wartości, a nie przez odniesienie?

Rozwiązaniem jest więc przesłonięcie ==
operatora i hashCode
tak:
class User {
final String? name;
final int? age;
const User({this.name, this.age});
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is User &&
runtimeType == other.runtimeType &&
name == other.name &&
age == other.age;
@override
int get hashCode => name.hashCode ^ age.hashCode;
}
A teraz, jeśli porównamy dwa niestałe User
obiekty, które mają te same wartości, wówczas instrukcja wyświetli true
.
A to dużo kodu standardowego!

Prostym sposobem osiągnięcia tego celu jest użycie pakietu Equatable .
- Dodaj równą zależność w
pubspec.yaml
swoim projekcie trzepotania:
dependencies:
flutter:
sdk: flutter
equatable: ^2.0.5
import 'package:equatable/equatable.dart';
class User extends Equatable {
const User({this.name, this.age});
final String? name;
final int? age;
@override
List<Object?> get props => [name, age];
}
Dziękuje za przeczytanie!
Youtube: Bekar Programista
