Ivo's answer works for general enum usage. But in my case I wanted to use json_serializable with enum where some enum values had different string/json key mapping. So I used JsonValue annotation over enum values as below:
enum Status {
active,
inactive,
pending,
@JsonValue('unknown_status') // Optional: custom JSON value for unknown
unknown,
}
and if you need a default enum value in case json string does not match then apply @JsonKey with unknownEnumValue param to the field in your serializable class using the enum, specifying the desired default value for unknownEnumValue.
part 'my_model.g.dart'; // Generated file
@JsonSerializable()
class MyModel {
final String name;
@JsonKey(unknownEnumValue: Status.unknown) // set 'unknown' as default
final Status status;
MyModel({required this.name, required this.status});
factory MyModel.fromJson(Map<String, dynamic> json) => _$MyModelFromJson(json);
Map<String, dynamic> toJson() => _$MyModelToJson(this);
}