Flutter 冻结,Unknown/Fallback 联合值
Flutter Freezed, Unknown/Fallback union value
是否可以在 freezed 中使用 FallBack/Unknown 联合构造函数?
假设我有这个联盟:
@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);
}
现在,我收到一个 JSON 和一个新的 'type',例如 'boat'。
当我调用Vehicle.fromJson时,我得到了一个错误,因为这会落入开关的“FallThroughError”。
是否有像 JsonKey 那样的注释?
@JsonKey(name: 'type', unknownEnumValue: VehicleType.unknown)
我知道我们有一个 'default' 构造函数,但是那个构造函数的 'type' 是 'default',所以 'boat' 不会出现在那个 switch case 上。
谢谢
您可以使用 fallbackUnion
属性来指定在这种情况下使用哪个 constructor/factory。
@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);
}
是否可以在 freezed 中使用 FallBack/Unknown 联合构造函数?
假设我有这个联盟:
@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);
}
现在,我收到一个 JSON 和一个新的 'type',例如 'boat'。
当我调用Vehicle.fromJson时,我得到了一个错误,因为这会落入开关的“FallThroughError”。
是否有像 JsonKey 那样的注释?
@JsonKey(name: 'type', unknownEnumValue: VehicleType.unknown)
我知道我们有一个 'default' 构造函数,但是那个构造函数的 'type' 是 'default',所以 'boat' 不会出现在那个 switch case 上。
谢谢
您可以使用 fallbackUnion
属性来指定在这种情况下使用哪个 constructor/factory。
@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);
}