Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

omit properties from toJson() when their value is an empty list #1369

Open
Dieterbe opened this issue Nov 13, 2023 · 1 comment
Open

omit properties from toJson() when their value is an empty list #1369

Dieterbe opened this issue Nov 13, 2023 · 1 comment

Comments

@Dieterbe
Copy link

Dieterbe commented Nov 13, 2023

I have a class like so (simplified/redacted):

class Source {
  final String? url;
  final List<String> works;

  Source({
    required this.url,
    required this.works,
  });

  Map<String, dynamic> toJson() => {
        if (url != null) 'url': url,
        if (works.isNotEmpty) 'works': works,
      };

I want to transition from my own handwritten toJson(), to a generated one.
for the url field i can use the includeIfNull: false option, but for the 2nd field, is there a similar option to omit lists if they are empty? i see no such option?

Likewise, is it possible to tolerate such a field not being set when decoding json, and setting it to [] on the object?

@lukehutch
Copy link

I added #1385 which is related to this.

What you propose would work for fields of type List<String>, but not List<String>? (although I think it's still a good idea for non-nullable lists, to save on serialization time and space).

This could be extended to other "empty types" such as the empty string (for String-typed fields that are not nullable), and even the integer value 0 (for numerical fields that are not nullable).

Also related: #1340

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants