Skip to content

includeIf #1114

Open
Open
@AlexanderFarkas

Description

@AlexanderFarkas

Is your feature request related to a problem? Please describe.
PATCH REST requests, for example, are hard to do.

Photo's null is meaningful. If we send photo == null, then the photo should be deleted on the server and replaced by a placeholder.

Also, if we want to update only the name, photo should remain untouched.

@JsonSerializable(includeIfNull: false)
class PatchUser {
  final String name;
  final String? photo;

  PatchUser(this.photo, this.name);
}

That wouldn't work, 'cause null has meaning.

class Wrapper<T> {
  final T value;

  Wrapper(this.value);

  T toJson() => value;
}

@JsonSerializable(includeIfNull: false)
class PatchUser {
  final String name;
  final String? photo;

  PatchUser(this.photo, this.name);
}

That wouldn't also, because includeIfNull applies after toJson is called.

Describe the solution you'd like

@JsonSerializable()
class PatchUser {
  final String name;
  
  @JsonKey(includeIf: _skipPhotoIf)
  final Wrapper<String?>? photo;

  PatchUser(this.photo, this.name);
}

bool _includeIf(Wrapper<String?>? value) => value != null;

Also for the whole thing:

@JsonSerializable(includeIf: _includeIf)
class PatchUser {
  final Wrapper<String>? name;
  final Wrapper<String?>? photo;

  PatchUser(this.photo, this.name);
}

bool _includeIf(Object? value) => !(value is Wrapper && value == null);

Additional Context
If this enhancement is welcome, I will be ready to make a PR.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions