Flutter 冻结,未知/后备联合值

Bru*_*nes 4 union json dart flutter freezed

是否可以在冻结中使用后备/未知联合构造函数?

可以说我有这个工会:

@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);
}
Run Code Online (Sandbox Code Playgroud)

现在,我收到一个带有新“类型”(例如“船”)的 JSON。

当我调用Vehicle.fromJson时,出现错误,因为这会陷入交换机的“FallThroughError”。

是否有任何注释,就像我们对 JsonKey 的注释一样?

@JsonKey(name: 'type', unknownEnumValue: VehicleType.unknown)
Run Code Online (Sandbox Code Playgroud)

我知道我们有一个“默认”构造函数,但该构造函数的“类型”是“默认”,因此“船”不会出现在该开关盒上。

谢谢

Mad*_*han 5

您可以使用fallbackUnion属性来指定在这种情况下使用哪个构造函数/工厂。


@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);
}

Run Code Online (Sandbox Code Playgroud)