Skip to content

Support integrating with built_collection #313

@xuanswe

Description

@xuanswe

built_collection is the official immutable collections library from Google.
Therefore, it would be nice if dart_mappable could officially maintain compatibility with built_collection.

This could be a separate package like dart_mappable_built_collection.

At least, before having a package like this, we can have example code in /dart_mappable/tree/main/examples so people can copy to their projects and use immediately.

Below is my initial code in my playground project with simple test cases.
As I am new to both built_collection and dart_mappable, so my code might not work correctly in edge cases.

import 'package:built_collection/built_collection.dart';
import 'package:dart_mappable/dart_mappable.dart';

void useBuiltCollectionMappers() {
  MapperContainer.globals.useAll([
    IterableMapper<BuiltList>(
      <T>(Iterable<T> i) => BuiltList.of(i),
      <T>(f) => f<BuiltList<T>>(),
    ),
    IterableMapper<BuiltSet>(
      <T>(Iterable<T> i) => BuiltSet.of(i),
      <T>(f) => f<BuiltSet<T>>(),
    ),

    // MapMapper doesn't work because `BuiltMap` doesn't implement `Map`
    BuiltMapMapper(),

    // TODO: implement mappers for other public types in built_collection
  ]);
}

class BuiltMapMapper extends SimpleMapper2<BuiltMap> {
  const BuiltMapMapper();

  @override
  BuiltMap<K, V> decode<K, V>(Object value) {
    if (value is Map) {
      return BuiltMap.of(value.cast<K, V>());
    }
    throw MapperException.unexpectedType(value.runtimeType, "Map");
  }

  @override
  Map<K, V> encode<K, V>(BuiltMap<K, V> self) {
    return self.asMap();
  }

  @override
  Function get typeFactory =>
      <K, V>(f) => f<BuiltMap<K, V>>();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions