How to disable Freezed to create fromJson and only generate toJson

61 Views Asked by At

I'm using the Freezed package in my Flutter project for immutable state management. I have a class VoucherRequestRM where I only want to generate the toJson method and not the fromJson method. Here's my current code:

@Freezed(fromJson: false)
class VoucherRequestRM with _$VoucherRequestRM {
  @JsonSerializable(fieldRename: FieldRename.snake, createFactory: false)
  factory VoucherRequestRM({
    required String voucher,
    required String userToken,
    required double price,
  }) = _VoucherRequestRM;

  factory VoucherRequestRM.fromJson(Map<String, dynamic> json) {
    throw UnimplementedError();
  }
}

As you can see, I've tried to disable the fromJson method by throwing an UnimplementedError. However, I'm not sure if this is the best approach. Is there a way to instruct Freezed to only generate the toJson method and completely skip generating the fromJson method?

Any help would be appreciated. Thanks in advance!

1

There are 1 best solutions below

0
Sébastien Gruhier On

add annoation to your field

   @JsonKey(includeFromJson: false, includeToJson: true)   
   required String voucher,

or for your all class use

    @Freezed(toJson: false, fromJson: true)