Skip to content

[Feature request] Support dart3 sealed class #1342

@lifeapps-42

Description

@lifeapps-42

Thank you for this package!

I failed to find any discussions about this and it feels like essential feture at this moment.

Do you have any plan to implement union-like sealed class serialization, so we can avoid using freezed?

We could use this feature something like this (inspired by freezed):

@JsonSerializable(unionKey: 'subtype') // dafualt 'runtimeType'
sealed class RootSealedClass {
  const RootSealedClass();

  factory RootSealedClass.fromJson(Map<String, dynamic> json) =>
      _$RootSealedClassFromJson(json);

  @JsonValue('first') // or literal class name as default
  const factory RootSealedClass.first(String someAtribute) =
      FirstSealedClassSubtype;

  @JsonValue('second') // or literal class name as default
  const factory RootSealedClass.second(int someOtherAtribute) =
      SecondSealedClassSubtype;

  Map<String, dynamic> toJson();
}

@JsonSerializable()
class FirstSealedClassSubtype extends RootSealedClass {
  const FirstSealedClassSubtype(this.someAtribute);

  factory FirstSealedClassSubtype.fromJson(Map<String, dynamic> json) =>
      _$FirstSealedClassSubtypeFromJson(json);

  final String someAtribute;

  @override
  Map<String, dynamic> toJson() => _$FirstSealedClassSubtypeToJson(this);
}

@JsonSerializable()
class SecondSealedClassSubtype extends RootSealedClass {
  const SecondSealedClassSubtype(this.someOtherAtribute);

  factory SecondSealedClassSubtype.fromJson(Map<String, dynamic> json) =>
      _$SecondSealedClassSubtypeFromJson(json);

  final int someOtherAtribute;

  @override
  Map<String, dynamic> toJson() => _$SecondSealedClassSubtypeToJson(this);
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions