Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switching from annotated to block style for fromJson() method allows @JsonSerializable() annotation usage #1119

Open
er0ckx opened this issue Aug 18, 2024 · 0 comments
Assignees
Labels
documentation Improvements or additions to documentation needs triage

Comments

@er0ckx
Copy link

er0ckx commented Aug 18, 2024

This came up in #463 as a solution and finally solved my issue; therefore, I think it's worth documenting.

When you need to have both the freezed and JsonSerializer() annotations on your class, your fromJson() factory declaration MUST use block form not annotation form.

// DO THIS
@freezed
@JsonSerializable(fieldRename: FieldRename.snake)
class MapPlace with _$MapPlace {
  const MapPlace._();

  const factory MapPlace({
    ...
  }) = _MapPlace;

  factory MapPlace.fromJson(Map<String, dynamic> json) {
    return _$MapPlaceFromJson(json);
  }
}
  // NOT THIS
  ...
  factory MapPlaceLocation.fromJson(Map<String, Object?> json) => 
    _$MapPlaceLocationFromJson(json);
  ...

I needed to use the "fieldRename" capability of the @JsonSerializer() annotation on a couple of my freezed classes. I kept getting errors like this. But once I changed to block form like described in #463 then everything worked.

lib/maps_service/model_places_nearby.g.dart:9:10: Error: '_$MapPlaceFromJson' is already declared in this scope.
MapPlace _$MapPlaceFromJson(Map<String, dynamic> json) => MapPlace(
         ^^^^^^^^^^^^^^^^^^
lib/maps_service/model_places_nearby.freezed.dart:178:10: Context: Previous declaration of '_$MapPlaceFromJson'.
MapPlace _$MapPlaceFromJson(Map<String, dynamic> json) {
         ^^^^^^^^^^^^^^^^^^
lib/maps_service/model_places_nearby.dart:35:7: Error: Can't use '_$MapPlaceFromJson' because it is declared more than once.
      _$MapPlaceFromJson(json);

Thanks,
Eric

@er0ckx er0ckx added documentation Improvements or additions to documentation needs triage labels Aug 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation needs triage
Projects
None yet
Development

No branches or pull requests

2 participants