목표
- 객체의 일부 속성만 변경하고 나머지는 그대로 유지하는 방법
copyWith
메서드를 활용하여 객체의 불변성을 유지하며 상태를 관리
1. 전체 코드
class User {
String? name;
int? age;
String? email;
User({required this.name, required this.age, required this.email});
User copyWith({String? name, int? age, String? email}){
return User(
name: name ?? this.name,
age: age ?? this.age,
email: email ?? this.email
);
}
}
void main() {
User state = User(name: "홍길동", age: 10, email: "ssar@nate.com");
// User changeState = User(name: state.name, age: 11, email: state.email);
User changeState = state.copyWith(age: 11);
state = changeState;
}
2. User
클래스 정의
- 속성:
name
,age
,email
- 생성자:
required
키워드로 모든 속성 필수 입력
class User {
String? name;
int? age;
String? email;
User({required this.name, required this.age, required this.email});
}
3. copyWith
메서드
- 목적: 기존 객체를 복사하여 일부 속성만 변경하는 메서드
- 설명:
null
값만 변경하고, 기존 객체 값은 그대로 유지
User copyWith({String? name, int? age, String? email}) {
return User(
name: name ?? this.name,
age: age ?? this.age,
email: email ?? this.email,
);
}
4. 사용 예시
state
객체 생성 후,copyWith
로age
만 변경한 새로운 객체changeState
생성
state
업데이트:state = changeState
void main() {
// 초기 객체 생성
User state = User(name: "홍길동", age: 10, email: "ssar@nate.com");
// copyWith로 age만 변경
User changeState = state.copyWith(age: 11);
// state 업데이트
state = changeState;
}
5. 핵심 개념
- 불변 객체 관리: 기존 객체를 변경하지 않고 새 객체를 생성하여 상태 변경
- 효율적 상태 관리:
copyWith
를 사용하여 변경할 속성만 수정하고, 나머지는 그대로 유지
Share article