Flutter Freezed, Unknown/Fallback union value

171

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

Share:
171
Bruno Antunes
Author by

Bruno Antunes

Updated on December 01, 2022

Comments

  • Bruno Antunes
    Bruno Antunes over 1 year

    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