Dart factory 3

factory 생성자에 대한 고찰2 - 일반 생성자와 다른 차이점

지난 시간에는 json 파싱할 때 factory 생성자를 왜 쓸까? 에 대한 포스팅을 했었다. 2023.09.21 - [🐦 Flutter] - factory 생성자에 대한 고찰1 - Json 파싱 근데 지난 포스팅에도 봤다시피 factory 생성자는 일반 생성자와는 다른 모양이었다. 그러니까 일반 생성자 는 객체를 다음과 같이 초기화할 수 있다. Album({this.userId, this.id, this.title}); 반면 factory 생성자 는 다음과 같이 초기화한다. factory Album.fromJson(Map json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); } factory 생성자는 ..

🐦 Flutter 2023.09.23

factory 생성자에 대한 고찰1 - Json 파싱

class Album { final int userId; final int id; final String title; Album({this.userId, this.id, this.title}); factory Album.fromJson(Map json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); } } json 파싱할 때 보통 위 예제처럼 factory 생성자를 사용한다. factory 생성자는 인터넷에 조금만 찾아도 "이미 생성된 인스턴스를 재활용하는 생성자" 라고 알고 있을 것이다. 위 예제는 사실상 factory 생성자를 굳이 안 써도 된다고 한다. factory 생성자를 json 파싱할때만 본 나..

🐦 Flutter 2023.09.21

[Dart] Factory Constructor

Factory Constructor Factory Constructor 는 특이하게도 메서드처럼 바디가 있음 무조건 현재 클래스의 인스턴스를 반환해줘야 함 void main(){ final parent = Parent(id: 1); print(parent.id); final child = Child(id: 3); print(child.id); } class Parent { final int id; Parent({ required this.id, }); factory Parent(int id) { return Parent(id: id); // error } } class Child extends Parent { Child({ required super.id, }); } 하지만 에러가 나는 것을 볼 수 있다..

🐦 Flutter 2022.12.11