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

Feature Request: default values #944

Closed
mars3142 opened this issue Nov 10, 2020 · 6 comments
Closed

Feature Request: default values #944

mars3142 opened this issue Nov 10, 2020 · 6 comments
Assignees
Labels

Comments

@mars3142
Copy link

I would like to use the serializer/deserializer for built value classes, but if the input data doesn't contain all values, it would be helpful to initialize the values with a value, instead of null - so every property needs to be marked as @nullable which is bad behavior..

What's the best way to do it, if it's already possible? If it's not possible a new attribute for @BuiltValueField like default would be fine.

@davidmorgan davidmorgan self-assigned this Nov 10, 2020
@davidmorgan
Copy link
Collaborator

You can use _initializeBuilder as shown here: #212 (comment)

It's not in the docs yet, sorry.

@mars3142
Copy link
Author

Did you read my request complete? I want to use:

final object = serializers.deserializeWith(MyClass.serializer, json);

So it's not possible to use it that way. Right?

@davidmorgan
Copy link
Collaborator

Yes, it will work, the deserializer uses builders so setting a default on the builder affects it.

@mars3142
Copy link
Author

@daohoangson So this code eg will do the trick?

factory Account([updates(AccountBuilder b)]) =>
  new _$Account((b) => b..name = 'default'..update(updates));

@davidmorgan
Copy link
Collaborator

Not the factory--the initializeBuilder part

 static void _initializeBuilder(MessageBuilder builder) => builder
    ..id = ''
    ..userId = ''
    ..content = ''
    ..urlMedia = ''
    ..createdAt = DateTime(1970, 1, 1)
    ..type = MessageType.none
    ..localId = '';

@davidmorgan
Copy link
Collaborator

Should be documented as part of #1051

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

No branches or pull requests

2 participants