Luca Cras
Luca Cras

Reputation: 91

Freezed class with enum property throws error upon trying to serialize

I have a freezed class that takes an enum in its constructor, but when trying to perform the jsonEncode method on this class, it fails with the following error:

The following JsonUnsupportedObjectError was thrown while handling a gesture: Converting object to an encodable object failed: Instance of 'InputType'

I have annotated my enum cases with JsonValue("...") but I do not see any generated code for the enum.

Is this a bug or am I doing something wrong?

Full example below:

@freezed
class Input with _$Input {
  const factory Input({
    @Default(0) int seconds,
    @Default(0) double bolus,
    @Default(0) double infusion,
    @Default(InputType.Bolus) currentInputType,
  }) = _Input;

  factory Input.fromJson(Map<String, dynamic> json) => _$InputFromJson(json);
}

enum InputType {
  @JsonValue("bolus")
  Bolus,
  @JsonValue("infusion")
  Infusion,
}

// When calling jsonEncode(someInput); throws the specified error.

Update: freezed needs the enum type specified in the factory constructor! Default value is not enough.

Upvotes: 9

Views: 10095

Answers (4)

Evgeny
Evgeny

Reputation: 139

try this

part 'input_type.g.dart';

@JsonEnum(alwaysCreate: true)
enum InputType {
  @JsonValue("Bolus")
  bolus,
  @JsonValue("Infusion")
  infusion,
}

or

enum InputType {
  bolus("bolus"),
  infusion("Infusion");

  const InputType(this.value);
  final String value;
}

String _inputToJson(InputType it) => it.value;
InputType _inputFromJson(String value) => InputType.values.firstWhere((it) => it.value == value);

@JsonKey(fromJson: _inputFromJson, toJson: _inputToJson) @Default(InputType.bolus) InputType currentInputType;

Upvotes: 1

buckleyJohnson
buckleyJohnson

Reputation: 489

I had this problem but it was only fixed when I restarted my IDE (Android Studio).

Upvotes: 0

Adamu Muktar
Adamu Muktar

Reputation: 93

From your code, I spotted that you omitted the type of the prop currentInputType, so append InputType to it as in below:

@Default(InputType.Bolus) InputType? currentInputType,

Upvotes: 1

Yevhen Samoilov
Yevhen Samoilov

Reputation: 159

Try to use @JsonKey(name: 'vote_count') instead

Upvotes: 2

Related Questions