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

toJson() isn't working as expected #1019

Closed
mhmzdev opened this issue Dec 15, 2023 · 1 comment
Closed

toJson() isn't working as expected #1019

mhmzdev opened this issue Dec 15, 2023 · 1 comment
Assignees
Labels
bug Something isn't working needs triage

Comments

@mhmzdev
Copy link

mhmzdev commented Dec 15, 2023

I have two freezed model classes as given below:

AuthMeta.dart

@freezed
class AuthMeta with _$AuthMeta {
  const factory AuthMeta({
    required String uid,
    required String fullName,
    required String username,
    required String imageUrl,
    required UserGender gender,
  }) = _AuthMeta;

  factory AuthMeta.fromJson(Map<String, Object?> json) =>
      _$AuthMetaFromJson(json);
}

Comment

@freezed
class Comment with _$Comment {
  const factory Comment({
    required String id,
    required String uid,
    required String comment,
    required AuthMeta authMeta,
    @Default(true) bool visible,
    @Default(false) bool pinned,
    required DateTime createdAt,
  }) = _Comment;

  factory Comment.fromJson(Map<String, Object?> json) =>
      _$CommentFromJson(json);
}

But when I do something like this:

final commentObject = Comment( // filled with values);
commentObject.toJson();

It won't do toJson() to the AuthMeta object inside it.

Work around

For the time being, what I did is in comment.g.dart:

Map<String, dynamic> _$$CommentImplToJson(_$CommentImpl instance) =>
    <String, dynamic>{
      'id': instance.id,
      'uid': instance.uid,
      'comment': instance.comment,
      'authMeta': instance.authMeta.toJson(), // Write thie manually
      'visible': instance.visible,
      'pinned': instance.pinned,
      'createdAt': instance.createdAt.toIso8601String(),
    };

Is there something I'm doing wrong? or is this expected? If it's expected is there any way I can force it to make .toJson() for any nested freezed model.
Or any reference in documentation?

@mhmzdev mhmzdev added bug Something isn't working needs triage labels Dec 15, 2023
@mhmzdev mhmzdev changed the title toJson() isn't working as expecte toJson() isn't working as expected Dec 15, 2023
@rrousselGit
Copy link
Owner

As per the documentation of JSON encoding, you have to enable explicit_to_json in JSON_Serializable

Be it in the build.yaml or using a custom JsonSerializable annotation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs triage
Projects
None yet
Development

No branches or pull requests

2 participants