OneOf<T>.byKey constructor

OneOf<T>.byKey(
  1. String key,
  2. Map<Object?, OneOfBuilder<T>> types, {
  3. OneOfBuilder<T>? otherwise,
})

Picks the shape by the value of key in the body.

key can be a dotted path such as 'data.type' to read a nested field. A field named exactly key wins over the path. The builder always gets the whole body. otherwise builds anything else.

FeedItem: OneOf<FeedItem>.byKey('type', {
  'post': PostItem.fromJson,
  'ad': AdItem.fromJson,
}),

Implementation

factory OneOf.byKey(
  String key,
  Map<Object?, OneOfBuilder<T>> types, {
  OneOfBuilder<T>? otherwise,
}) => OneOf(
  (json, response) => (types[_readKey(json, key)] ?? otherwise)?.call(json),
);