google / google/built_value.dart

Add support for custom built collections

Open
#822 4 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

I recently had to make a custom built collection. However it seems to be impossible to make built_value treat such a class similar to `BuiltList` or `BuiltSet`, because there are a number of places where these collections are hard coded. Here are the improvements I would like to suggest:

### Generated `Builder`s of `Built` classes should have the corresponding builder type for attributes that are of the custom built collection type.
Suppose you have a built class `Foo` with a `BuiltList` of `Bar`:
```dart
abstract class Foo implements Built<...> {
...
BuiltList get bars;
}
```
In this case you coud do `Foo((b) => b.bars.add(Bar()))`. If the `BuiltList` was a `CustomBuiltList` you would have to do `Foo((b) => b.bars = CustomListBuilder()..add(Bar()).build())`.

### The serializer for the custom built collection should be automatically added to the generated serializers
When using the generated serializers, one would have to add the serializer for the `CustomBuildList` manually:
```dart
@SerializersFor([Foo, Bar])
final Serializers serializers = (_$serializers.toBuilder()
..add(CustomBuildListSerializer()))
.build();
```
For any standard build collection this would not have to be done.

### Builder factories for the builder of the custom built collection should be automatically added to the generated serializers
Again using the example above, a builder factory has to be manually added for every type the custom collection is used with.
```dart
@SerializersFor([Foo, Bar])
final Serializers serializers = (_$serializers.toBuilder()
..add(CustomBuildListSerializer()))
..addBuilderFactory(
const FullType(CustomBuildList, [FullType(Bar)]),
() => CustomListBuilder(),
)
.build();
```
This should also be generated.

### `StandardJsonPlugin` should be able to handle custom built collections
Currently the `StandardJsonPlugin` has a hard coded check for `BuiltList` and `BuiltSet` in `afterSerialize`. When trying to serialize a custom built collection similar to a list, this causes the given `List` to be treated like a map with alternating keys and values. This results in a faulty serialization as a json object instead of a list.

----

I might have missed some things where the built collections seem to be hard coded in. Basically one should be able to write a custom built collection that behaves identically to one from the `built_collection` package.

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.