flutterdartfreezedflutter-freezed

Let freezed use factory on initializing


I have a freezed class

@freezed
class Lobby with _$Lobby implements DataObject {
  @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
  const factory Lobby({
    Redirect? redirect,
  }) = _Lobby;
  const Lobby._();

  factory Lobby.fromJson(Map<String, dynamic> json) => _$LobbyFromJson(json);
}

and an enum

enum Redirect {
  test1('/thisistest1'),
  test2('/thisistest2'),

  const Redirect(this.path);

  factory Redirect.fromPath(String path) {
    return values.firstWhere((e) => e.path == path);
  }

  final String path;
}

When constructing my Lobby-Class I use the fromJson factory. In my Json I have the path and not the Redirect enum so I need to translate that.

Can I either tell freezed to use the Redirect.fromPath factory or can I somehow change the .fromJson accordingly?

What would be the best approach?

EDIT I have this data json in my edge-case, this is the print

{redirect: null}

And I am calling Lobby.fromJson(data)


Solution

  • You could try JsonConverter:

    enum Redirect {
      test1('/thisistest1'),
      test2('/thisistest2');
    
      const Redirect(this.path);
    
      factory Redirect.fromPath(String path) => values.firstWhere((e) => e.path == path);
    
      final String path;
    }
    
    class RedirectStringToEnumConvertor implements JsonConverter<Redirect?, String?> {
      const RedirectStringToEnumConvertor();
    
      @override
      Redirect? fromJson(String? json) => json == null? null : Redirect.fromPath(json);
    
      @override
      String? toJson(Redirect? object) => object?.toString();
    }
    
    @freezed
    @JsonSerializable(fieldRename: FieldRename.snake, explicitToJson: true)
    class Lobby with _$Lobby implements DataObject {
      const factory Lobby({
        @RedirectStringToEnumConvertor() Redirect? redirect,
      }) = _Lobby;
    
      const Lobby._();
    
      factory Lobby.fromJson(Map<String, dynamic> json) => _$LobbyFromJson(json);
    }
    

    More info freezed