google / google/built_value.dart
Deserialize to a Builder
- Dominant language
- Dart
- Stars
- 886
- Forks
- 195
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 4
Description
## Problem statement
Automatically deserialize objects with additional information inferred from context. E.g.: deserialize an entity from database, then immediately assign "key" property which is not in object's JSON but is known to the code calling deserializer:
Example
```dart
// { ...
// "42abef": {
// "name": "Andreas"
// }
// }
class Person implements Built {
String get name; // deserialized automatically.
String? get key; // known to deserialize caller, but must be nullable to allow deserialization.
static Serializer get serializer => _$personSerializer;
}
```
Marking those extra fields nullable forces all uses to add a null check operator (`person.key!`).
## Proposal
Deserialize to a Builder, rather than the model itself, then have the library user's code assign missing field and call `.build()`:
```dart
final person = serializers.deserializeWith(Person.serializer, snapshot.value)..key = currentKey..build();
```
Alternatively, have the `deserialize` method take a Builder with some fields already assigned, then backfill it and ship back the ready model.
```dart
final person = serializers.deserializeWith(Person.serializer, PersonBuilder(key: currentKey), snapshot.value);
```
Contributor guide
Assessment
This issue has not been assessed yet.