encodingStatement static method

String encodingStatement(
  1. LibraryElement library,
  2. DartType type,
  3. String codec,
  4. String value, {
  5. bool nonNull = false,
})

Implementation

static String encodingStatement(
  LibraryElement library,
  DartType type,
  String codec,
  String value, {
  bool nonNull = false,
}) {
  if (type.nullabilitySuffix == NullabilitySuffix.question && !nonNull) {
    return '$codec.encodeNullable($value, ${encodingFunction(library, type, codec, nonNull: true)})';
  }

  if (type.element == null) {
    throw Exception('Invalid type for encoding: $type');
  }

  if (TypeChecker.typeNamed(Data).hasAnnotationOf(type.element!)) {
    return '$value.toJson()';
  }

  if (type.isDartCoreList) {
    final valueType = (type as ParameterizedType).typeArguments[0];
    final typeName =
        typeImportPrefix(valueType, library) +
        typeExpression(valueType, library);

    final encodeItem = encodingFunction(library, valueType, codec);
    return '$codec.encodeList<$typeName>($value, $encodeItem)';
  } else if (type.isDartCoreMap) {
    final valueType = (type as ParameterizedType).typeArguments[1];
    final typeName =
        typeImportPrefix(valueType, library) +
        typeExpression(valueType, library);

    final encodeItem = encodingFunction(library, valueType, codec);
    return '$codec.encodeMap<$typeName>($value, $encodeItem)';
  } else {
    return '${encodingFunction(library, type, codec)}($value)';
  }
}