같은 Class의 다른 생성자로 redirect하고, Redirecting 생성자는 body없이 class name대신 this를 : 뒤에 사용한다.
Named constructors와 Initialized list를 혼용한 듯하다.
class Person {
int? id;
String name;
String birthday;
int? age;
// The main constructor for this class
Person({this.id, required this.name, required this.birthday, this.age});
// Redirecting Constructor
Person.clone(Person person) :
this(
id: person.id,
name: person.name,
birthday: person.birthday,
age: person.age
);
Map<String, dynamic> toMap() {
return {
"id": id,
"name": name,
"birthday": birthday,
//"age": age,
};
}
}
void main() {
Person p1 = Person(id: 1, name: "Aiden", birthday: "2020/01/01", age: 2);
Person p2 = p1;
print(p1.age);
print(p2.age);
p1.age = 3;
print(p1.age);
print(p2.age);
print("-------------------------");
Person p3 = Person.clone(p1);
print(p1.age);
print(p3.age);
p1.age = 1;
print(p1.age);
print(p3.age);
}
2
2
3
3
-------------------------
3
3
1
3 <- 다르다
https://dart.dev/language/constructors#redirecting-constructors