freezed icon indicating copy to clipboard operation
freezed copied to clipboard

fromJson cast error with nested Freezed Classes

Open WesselvanDam opened this issue 6 months ago • 0 comments

Describe the bug I get the following error:

Error: type '_Map<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' in type cast

Because I have a freezed class that has another freezed class as one of its fields, and the generated code does not correctly cast the JSON field of the parent class's fromJSON.

To Reproduce

Simplified code:

The parent class, UserModel:

@freezed
class UserModel with _$UserModel {
  @JsonSerializable(explicitToJson: true)
  const factory UserModel({
    @Default(CustomClaimsModel()) CustomClaimsModel customClaims,
  }) = _UserModel;
  const UserModel._();

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

child class, CustomClaimsModel:

@freezed
class CustomClaimsModel with _$CustomClaimsModel {
  @JsonSerializable(explicitToJson: true)
  const factory CustomClaimsModel({
    @Default(false) bool admin,
  }) = _CustomClaimsModel;

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

Expected behavior I expect the parent class UserModel to be able to generate an instance of CustomClaimsModel using its fromJson method, which should use the CustomClaimsModel's fromJson method for the value of the field customClaims. If I change all references of Map<String, dynamic> in the code of CustomClaimsModel and its generated files to Map, the code works and I do not get the error. Hence, I suspect that the casting of the JSON to the Map is faulty. Let me know if I'm missing something!

WesselvanDam avatar Aug 12 '24 17:08 WesselvanDam