Equatable Package

샤워실의 바보·2024년 3월 24일
0
post-thumbnail
// person.dart
import 'package:equatable/equatable.dart';

class Person extends Equatable {
  final int id;
  final String name;
  final String email;
  const Person({
    required this.id,
    required this.name,
    required this.email,
  });

  
  String toString() => 'Person(id: $id, name: $name, email: $email)';

  Person copyWith({
    int? id,
    String? name,
    String? email,
  }) {
    return Person(
      id: id ?? this.id,
      name: name ?? this.name,
      email: email ?? this.email,
    );
  }

  
  List<Object> get props => [id, name, email];
}

// person_page.dart
import 'package:flutter/material.dart';
import 'package:section3/models/person.dart';

class PersonPage extends StatelessWidget {
  const PersonPage({super.key});

  
  Widget build(BuildContext context) {
    const person1 = Person(id: 1, name: 'john', email: 'john@gmail.com');
    final person2 = person1.copyWith(id: 2, email: 'johndoe@gmail.com');
    const person3 = Person(id: 1, name: 'john', email: 'john@gmail.com');

    print(person1);
    print(person2);
    print(person1 == person3);
    print(person1.hashCode);
    print(person3.hashCode);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Person'),
      ),
    );
  }
}

이 코드의 핵심은 Equatable 패키지를 사용하는 것입니다. Equatable을 사용하면, Dart의 기본 == 연산자와 hashCode 메소드의 동작을 커스터마이징할 수 있으며, 객체의 동등성 비교를 위한 속성들을 명시적으로 정의할 수 있습니다. 이는 Flutter 및 Dart에서 더욱 효율적이고 직관적인 상태 관리와 데이터 비교를 가능하게 합니다.

Equatable의 동작 원리

Equatable 패키지는 객체의 동등성을 비교할 때, 개발자가 props 리스트에 명시한 속성들만을 사용합니다. 이 리스트에 있는 속성들이 같으면, 두 객체는 동등한 것으로 간주됩니다. 이는 개발자가 명시적으로 어떤 필드가 객체의 동등성을 결정하는지 제어할 수 있게 해 줍니다.

예제 코드 분석


List<Object> get props => [id, name, email];

위 코드에서 Person 클래스는 Equatable을 확장하고, props를 오버라이드하여 id, name, email을 포함시킵니다. 따라서, 이러한 세 속성이 모두 같은 경우 두 Person 객체는 동등하다고 판단됩니다.

const person1 = Person(id: 1, name: 'john', email: 'john@gmail.com');
const person3 = Person(id: 1, name: 'john', email: 'john@gmail.com');
print(person1 == person3); // true

person1person3은 모두 같은 id, name, email 값을 가지므로, Equatable에 의해 동등한 것으로 평가됩니다. 이것이 print(person1 == person3);true를 출력하는 이유입니다.

hashCode의 동등성

hashCode는 객체가 동등할 때 같은 값을 반환해야 합니다. Equatable을 사용하면, props에 명시된 속성들을 기반으로 hashCode를 자동으로 계산합니다. 따라서, 동등한 객체는 같은 hashCode 값을 가집니다. 이는 person1person3이 같은 hashCode 값을 갖는 이유입니다.

결론

Equatable 패키지를 사용함으로써, Person 객체들이 id, name, email 값의 조합에 기반한 동등성 비교를 수행하게 됩니다. 따라서, person1person3이 동일한 값을 가지므로 동등하게 평가되며, 이로 인해 true가 출력되고, 같은 hashCode 값을 갖게 됩니다. 이는 코드의 가독성과 유지 보수성을 향상시키며, 복잡한 상태 관리 로직에서의 버그를 줄일 수 있습니다.

profile
공부하는 개발자

0개의 댓글