Rohan Taneja
Rohan Taneja

Reputation: 10677

dart freezed @Default doesn't apply defaultValue on JsonKey

I have a class called Player (player.dart) that has a field called isCaptain:

@JsonKey(name: "is_captain") @Default(false) bool isCaptain,

The line above produces the following in player.g.dart:

isCaptain: json['is_captain'] as bool,

When I create a Player object using Player.fromJson(playerJson) that's missing the is_captain key, isCaptain is set to null on the Player object instead of false as provided by @Default.

When I add defaultValue: false to the @JsonKey(...) as follows:

@JsonKey(name: "is_captain", defaultValue: false) @Default(false) bool isCaptain,

...the implementation in player.g.dart changes to:

isCaptain: json['is_captain'] as bool? ?? false,

Now everything works as expected and if is_captain is not present in the API response, isCaptain gets the default value of false.

I'm confused because freezed's documentation says that adding @Default automatically adds defaultValue to the @JsonKey(...) too but that doesn't seem to be the case here. What am I missing?

Upvotes: 0

Views: 2595

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 276947

Freezed adds an implicit JsonKey with the default value.

Your issue is that you passed a custom JsonKey. In which case, your annotation takes over what Freezed auto-generates.

So by specifying a JsonKey, you basically removed the implicit default value added by Freezed.

Upvotes: 1

Related Questions