serialize method

  1. @override
String? serialize(
  1. DartType targetType,
  2. String expression,
  3. TypeHelperContextWithConfig context
)
override

Returns Dart code that serializes an expression representing a Dart object of type targetType.

If targetType is not supported, returns null.

Let's say you want to serialize a class Foo as just its id property of type int.

Treating expression as a opaque Dart expression, the serialize implementation could be a simple as:

String serialize(DartType targetType, String expression) =>
  "$expression.id";
```.

Implementation

@override
String? serialize(
  DartType targetType,
  String expression,
  TypeHelperContextWithConfig context,
) {
  if (!coreMapTypeChecker.isAssignableFromType(targetType)) {
    return null;
  }
  final args = targetType.typeArgumentsOf(coreMapTypeChecker)!;
  assert(args.length == 2);

  final keyType = args[0];
  final valueType = args[1];

  _checkSafeKeyType(expression, keyType);

  final subFieldValue = context.serialize(valueType, closureArg);
  final subKeyValue =
      _forType(keyType)?.serialize(keyType, _keyParam, false) ??
          context.serialize(keyType, _keyParam);

  if (closureArg == subFieldValue && _keyParam == subKeyValue) {
    return expression;
  }

  final optionalQuestion = targetType.isNullableType ? '?' : '';

  return '$expression$optionalQuestion'
      '.map(($_keyParam, $closureArg) => '
      'MapEntry($subKeyValue, $subFieldValue))';
}