0

I'm using Freezed to generate my models. I want to ignore a specific key, so I'm using @JsonKey(ignore: true).

@freezed
class ObjectA with _$ObjectA {
  const factory ObjectA({
    @JsonKey(ignore: true) 
    List<ObjectB> ObjectBList,
  }) = _ObjectA;

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

When I try to run the build_runner, I'm getting the above exception:

The parameter ObjectBList of ObjectA. is non-nullable but is neither required nor marked with @Default

Why doesn't it been ignored?

genericUser
  • 4,417
  • 1
  • 28
  • 73

1 Answers1

1

The issue you are facing is with Dart syntax. When you declare parameters in constructors. You can have a nullable parameter or a non-nullable parameter; this also apply to variables.

If you want the parameter you declared in the constructor to be non-nullable then it must either have a default value or the declared parameter must be prefixed with the required keyword.

You have three options:

  • Add the required keyword required List<ObjectB> ObjectBList
  • Make it nullable List<ObjectB>? ObjectBList
  • Give it a default value. With freezed this can be done with the @Default annotation @Default([]) List<ObjectB> ObjectBList
davidn
  • 378
  • 4
  • 12
  • 1
    The `@JsonKey()` annotation is meant for serialization. It tells `json serializable` how to handle that parameter when building the `toJson` and `fromJson` methods – davidn Oct 23 '22 at 17:56
  • my list can be null. I tried to use Default([]) List list. But its giving error in freezed.g file. How can i handle this? – Hadi Khan Jul 05 '23 at 11:50
  • @HadiKhan If your list can be null, then you don't need a default value. You can remove the `Default([])` – davidn Jul 05 '23 at 12:43
  • Wont it throw error? Sometimes list is null for some json objects. I am not able to write a model like List list. I am forced to write List? list. When i want to display the list itme model.list!.item it will throw error that null check operator was used on null. model.list.item wont work – Hadi Khan Jul 05 '23 at 15:00
  • I don't understand. You should ask a new question describing in detail the challenge you are facing @HadiKhan – davidn Jul 05 '23 at 15:38