fix: `Enum` with `int` type cannot be stored
Description
When I used @JsonValue to specify int value to an enum entry, the value cannot be stored and the retrieved value will always be empty.
Steps To Reproduce
- Annotate enum values with
@JsonValueof typeint
enum Step{
@JsonValue(1)
step1,
@JsonValue(2)
step2,
@JsonValue(3)
step3,
}
- Create a param in
Statewith typeMap<Step, String>
@freezed
class RegisterState with _$RegisterState {
factory RegisterState ({
@Default({}) Map<Step, String> registerSteps,
}) = _RegisterState;
factory RegisterState .fromJson(Map<String, dynamic> json) => _$RegisterStateFromJson(json);
}
- Modify
State
emit(state.copyWith(
registerSteps: {
Step.step1: 'done',
Step.step2: 'doing',
Step.step3: 'none',
},
)
- Hot Restart to check state
Expected Behavior
The state should be
registerSteps: {
Step.step1: 'done',
Step.step2: 'doing',
Step.step3: 'none',
},
Actual Behavior
The state showed
registerSteps: {},
Additional Context
The problem is in the method dynamic _traverseComplexJson(dynamic object),
} else if (object is Map) {
_checkCycle(object);
final map = <String, dynamic>{};
object.forEach((dynamic key, dynamic value) {
final castKey = _cast<String>(key);
if (castKey != null) {
map[castKey] = _traverseWrite(value).value;
}
});
_removeSeen(object);
return map;
}
The map's key is type int so it cannot be casted to String so the value will not be stored
I did some investigating and found it's related to this issue. It happens only on enums, and works fine on other JsonSerialize supported types.
https://github.com/google/json_serializable.dart/blob/85e83641befab6a30526c24950ecfd3fe3f9ce62/json_serializable/README.md?plain=1#L159-L160