Dart Równość i Pakiet Equatable

Nov 27 2022
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 == zwraca wartość true, w przeciwnym razie zwraca wartość false.

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 trueprzeciwnym razie ocenia na false.

W Dart domyślnie ==operator sprawdza równość referencyjną i ocenia, truekiedy 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.

  1. Stwórzmy Userklasę:
  2. 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 hashCodetak:

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 Userobiekty, 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 .

  1. Dodaj równą zależność w pubspec.yamlswoim projekcie trzepotania:
  2. 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