Reputation: 49
Is it possible to use a FallBack/Unknown union contructor in freezed?
Lets say I have this union:
@Freezed(unionKey: 'type')
@freezed
abstract class Vehicle with _$Vehicle {
const factory Vehicle() = Unknown;
const factory Vehicle.car({int someVar}) = Car;
const factory Vehicle.moto({int otherVar}) = Moto;
factory Vehicle.fromJson(Map<String, dynamic> json) => _$VehicleFromJson(json);
}
And now, I receive a JSON with a new 'type', 'boat' for example.
When I call Vehicle.fromJson, I got an error, because this will fall into the "FallThroughError" of the switch.
Is there any anotation for this, like we have for JsonKey?
@JsonKey(name: 'type', unknownEnumValue: VehicleType.unknown)
I known that we have a 'default' constructor, but the 'type' for that one is 'default', so 'boat' will not be on that switch case.
Thanks
Upvotes: 4
Views: 989
Reputation: 7458
You can use fallbackUnion
attribute to specify which constructor/factory to use in such a case.
@Freezed(unionKey: 'type', fallbackUnion: "Unknown")
@freezed
abstract class Vehicle with _$Vehicle {
const factory Vehicle() = Unknown;
const factory Vehicle.car({int someVar}) = Car;
const factory Vehicle.moto({int otherVar}) = Moto;
// Name of factory must match what you specified, case sensitive
// if you're using a custom 'unionKey', this factory can omit
// @FreezedUnionValue annotation if its dedicated for an unknown union.
const factory Vehicle.Unknown(
/*think params list need to be empty or must all be nullable/optional*/
) = _Unknown;
factory Vehicle.fromJson(Map<String, dynamic> json) => _$VehicleFromJson(json);
}
Upvotes: 6