chichi
chichi

Reputation: 3292

Flutter: how to apply defaultValue when I create a model with null value when using json_serializable?

@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?

Upvotes: 1

Views: 1609

Answers (1)

Jahidul Islam
Jahidul Islam

Reputation: 12565

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

Upvotes: 2

Related Questions