본문 바로가기
개발/Flutter

freezed factory 생성자

by dev_caleb 2023. 5. 5.
728x90

freezed로 data class 만들어서 통신하려고 하는데, 

일일이 type을 지정해주기 귀찮아서 생성자를 나누고 싶었는데, 어떻게 해야될 지 잘 몰라서 고민하다가 

 

freezed 공홈에 가서 찾아봤다. 

 

일단 나는 해당 부분을 찾아서 만들어줬으나, property가 다를 때 오류가 생길 수 있다는 것을 확인했다. 

 

import 'package:freezed_annotation/freezed_annotation.dart';

part 'point_noti_dto.freezed.dart';
part 'point_noti_dto.g.dart';

@freezed
class PointNotiDTO with _$PointNotiDTO {
  factory PointNotiDTO.xp({
    required String uid,
    required num point,
    required String description,
    required String routes,
    required String type,
    @Default('xp') String pointClass,
  }) = _PointNotiDTOXp;

  factory PointNotiDTO.gold({
    required String uid,
    required num point,
    required String description,
    required String routes,
    required String type,
    @Default('gold') String pointClass,
  }) = _PointNotiDTOGold;

  factory PointNotiDTO.diamond({
    required String uid,
    required num point,
    required String description,
    required String routes,
    required String type,
    @Default('gold') String pointClass,
  }) = _PointNotiDTODiamond;

  factory PointNotiDTO.fromJson(Map<String, dynamic> json) => _$PointNotiDTOFromJson(json);
}

일단 내 코드 -> 문제 없다..

 

공홈의 글을 읽어보자면, 같은 name property는 이렇게 불러올 수 있는데, 다른 property는 가져올 수 없다는 것.(그럼 어떻게 쓰냐..)

 

copywith도 마찬가지란다.

이문제를 해결하기 위해서는  object의 상태를 체크해야한다.(패턴매칭)

non - shared properties에 패턴매칭 사용,

다음 union을 생각해보자(위에 것이랑 같은 것 같은데?)

solution이 있다.

아래 쪽에 쭉.. 있구만, 

 

다행히 나는 저 상황이 아니라서 다행이다. 왜냐하면 사용할 때 코드가 너무 길기 때문이다. 

아무튼, 같은 property로 만들어주면 문제가 없는 듯하다! 

 

 

728x90

'개발 > Flutter' 카테고리의 다른 글

android -> flutter button 비활성화 되었을 때  (0) 2023.05.07
flutter secure storage  (0) 2023.05.05
Flutter upgrade 체크 및 실행  (0) 2023.05.03
mobile app architecture pattern  (0) 2023.04.28
drag할 때 keyboard 가리기  (0) 2023.04.27