Search code examples
flutternsjsonserializationflutter-freezed

Flutter ignore field using Freezed


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?


Solution

  • 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