bloc icon indicating copy to clipboard operation
bloc copied to clipboard

fix: `Enum` with `int` type cannot be stored

Open weeb-destroyer opened this issue 2 years ago • 1 comments

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

  1. Annotate enum values with @JsonValue of type int
enum Step{
  @JsonValue(1)
  step1,
  @JsonValue(2)
  step2,
  @JsonValue(3)
  step3,
}
  1. Create a param in State with type Map<Step, String>
@freezed
class RegisterState with _$RegisterState {
  factory RegisterState ({
    @Default({}) Map<Step, String> registerSteps,
  }) = _RegisterState;

  factory RegisterState .fromJson(Map<String, dynamic> json) => _$RegisterStateFromJson(json);
}
  1. Modify State
emit(state.copyWith(
        registerSteps: {
          Step.step1: 'done',
          Step.step2: 'doing',
          Step.step3: 'none',
        },
)
  1. 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

weeb-destroyer avatar Oct 19 '23 04:10 weeb-destroyer

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

brian030128 avatar Oct 19 '23 21:10 brian030128