플러터(1)
JsonSerializable
factory 생성자 이론
- 매번 인스턴스를 새롭게 생성하는 constructor와 다르게 기존에 이미 생성된 인스턴스가 있다면 재사용
- 싱글톤 패턴
- this에 접근 불가능
class Human {
    final String gender;
    final String age;
    final String name;
 	
    Human.name(String name) : this(name : name);
    //기존 생성자와 이름을 다르게
    factory Human.name(String name){
    	return Man(name);
    }
}
class Man extands Human {
	Man(String name) : super(name : name);
}
JsonSerializable
- 
    dependency 추가(https://github.com/google/json_serializable.dart/tree/master/example) dependencies: json_annotation: ^4.8.0 dev_dependencies: build_runner: ^2.3.3 json_serializable: ^6.6.0
기존 코드 - json으로 받아오는 데이터를 직렬화 해주는 패키지
class ExampleInfo{
    final int one;
    final int two;
    ExampleInfo({
        required this.one,
        reqiired this.two
    });
    factory ExampleInfo.fromJson(Map<String, dynamic> json) {
        return ExampleInfo(
        oen: json["one"] as int,
        two: json["two"] as int,
        );
  }
}
개선 코드 - @JsonSerializable을 이용한 방법
part "example_info.g.dart";
@JsonSerializable()
class Example{
    final int one;
    final int two;
    Example({
        required this.one,
        reqiired this.two
    });
    factory Example.fromJson(Map<String, dynamic> json) {
        return _$ExampleInfo(json);
    }
    Map<String,dynamic> toJson() => _$ExampleInfoToJson(this);
}
- part는 “현재파일명.g.dart”
- Example.fromJson -> json에서 모델로 변환
- toJson() -> 모델에서 json으로 변환
- 변경 후 flutter pub run build_runner build 코드를 터미널에서 실행
Leave a comment