google / google/built_value.dart

Deserialize to a Builder

Open
#1,156 2 comments 0 reactions 1 assignee Claimed by @davidmorgan View on GitHub
p2 / feature request
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.