Home > database >  Flutter: how to apply defaultValue when I create a model with null value when using json_serializabl
Flutter: how to apply defaultValue when I create a model with null value when using json_serializabl

Time:11-28

@JsonSerializable()
class TestModelA {
  @JsonKey(defaultValue: 'jp')
  final String? language;
  @JsonKey(defaultValue: 'jp')
  final String? location;

  TestModelA(this.language, this.location);

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

  Map<String, dynamic> toJson() => _$TestModelAToJson(this);
}

I have this JsonSerializable() with the @JsonKey defaultValue. How can I assign that default value?

When I create the model with null values, it just sets with the null values. How can I create TestModelA by assigning defaultValues?

CodePudding user response:

Try the below code. JSON if null then pass the values using constructor

factory TestModelA.fromJson(Map<String, dynamic> json) =>
      json!=null? _$TestModelAFromJson(json): TestModelA("English","US");
  • Related