dart freezed default for empty class

1,276

Note the Player.blank() constructor below. Like this...

@freezed
class Player with _$Player {
  Player._();
  factory Player({
    @Default('') String handle,
    @Default('') String realname,
    Contact? contactinfo,
    @Default(false) bool emailverified,
    @Default(false) bool showemail,
    @Default(false) bool showphone,
    @Default('') String avatarurl,
    DateTime? datejoined,
    @Default(0) int transactions,
    DateTime? datelasttransaction,
    DateTime? datelastlogin,
    @Default([]) List<String> tags,
    @Default([]) List<String> leagues,
    @Default([]) List<String> events,
    @Default(0) int views,
    @Default(0) int likes,
    @Default(0) int loginfails,
    @JsonKey(ignore: true) @Default('') String password,
    @JsonKey(ignore: true) @Default('') String confirm,
    required Meta meta,
  }) = _Player;
  factory Player.blank() => Player(contactinfo: Contact(), meta: Meta());
  factory Player.fromJson(Map<String, dynamic> json) => _$PlayerFromJson(json);
Share:
1,276
FeelRightz
Author by

FeelRightz

Updated on December 01, 2022

Comments

  • FeelRightz
    FeelRightz 1 day
      @freezed
      class ABCModel with _$ABCModel {
        factory ABCModel({
          @JsonKey(name: "id") @Default('') String id,
          @JsonKey(name: "name") @Default('') String name,
        }) = _ABCModel;
        factory ABCModel.fromJson(Map<String, dynamic> json) => _$ABCModelFromJson(json);
      }
      @freezed
      class EFGModel with _$EFGModel {
        factory EFGModel({
          @JsonKey(name: "abc") @Default(ABCModel()) ABCModel abc, //empty ABCModel
        }) = _EFGModel;
        factory EFGModel.fromJson(Map<String, dynamic> json) => _$EFGModelFromJson(json);
      }
    

    If EFGModel get an empty or null abc json value, what is the suitable value to put on @Default() freezed annotation, @Default(ABCModel()) is not correct

    • Abion47
      Abion47 over 1 year
      It's whatever makes sense for the default to be. We can't read your mind and know what purpose this class serves or the significance of the data is, so the decision is up to you.
    • FeelRightz
      FeelRightz over 1 year
      if put @Default(ABCModel()) will get error
    • Abion47
      Abion47 over 1 year
      And that error is?
    • Locohost
      Locohost over 1 year
      Yeah I struggled a while with this too. I ended up making them without default. Like: ABCModel? abc, and left them null. Then made a named factory constructor that filled in the model props.