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 (!coreIterableTypeChecker.isAssignableFromType(targetType)) {
    return null;
  }

  final itemType = coreIterableGenericType(targetType);

  // This block will yield a regular list, which works fine for JSON
  // Although it's possible that child elements may be marked unsafe

  var isList = _coreListChecker.isAssignableFromType(targetType);
  final subField = context.serialize(itemType, closureArg)!;

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

  // In the case of trivial JSON types (int, String, etc), `subField`
  // will be identical to `substitute` – so no explicit mapping is needed.
  // If they are not equal, then we to write out the substitution.
  if (subField != closureArg) {
    final lambda = LambdaResult.process(subField);

    expression = '$expression$optionalQuestion.map($lambda)';

    // expression now represents an Iterable (even if it started as a List
    // ...resetting `isList` to `false`.
    isList = false;

    // No need to include the optional question below – it was used here!
    optionalQuestion = '';
  }

  if (!isList) {
    // If the static type is not a List, generate one.
    expression += '$optionalQuestion.toList()';
  }

  return expression;
}