writeClassDecode method

  1. @override
void writeClassDecode(
  1. KotlinOptions generatorOptions,
  2. Root root,
  3. Indent indent,
  4. Class classDefinition, {
  5. required String dartPackageName,
})
override

Writes a single class decode method to indent.

Implementation

@override
void writeClassDecode(
  KotlinOptions generatorOptions,
  Root root,
  Indent indent,
  Class classDefinition, {
  required String dartPackageName,
}) {
  final String className = classDefinition.name;

  indent.write('companion object ');
  indent.addScoped('{', '}', () {
    indent.writeln('@Suppress("LocalVariableName")');
    indent
        .write('fun fromList(${varNamePrefix}list: List<Any?>): $className ');

    indent.addScoped('{', '}', () {
      enumerate(getFieldsInSerializationOrder(classDefinition),
          (int index, final NamedType field) {
        final String listValue = '${varNamePrefix}list[$index]';
        final String fieldType = _kotlinTypeForDartType(field.type);

        if (field.type.isNullable) {
          if (field.type.isEnum) {
            indent.write('val ${field.name}: $fieldType? = ');
            indent.add('($listValue as Int?)?.let ');
            indent.addScoped('{ num ->', '}', () {
              indent.writeln('$fieldType.ofRaw(num)');
            });
          } else {
            indent.writeln(
                'val ${field.name} = ${_cast(indent, listValue, type: field.type)}');
          }
        } else {
          if (field.type.isEnum) {
            indent.writeln(
                'val ${field.name} = $fieldType.ofRaw($listValue as Int)!!');
          } else {
            indent.writeln(
                'val ${field.name} = ${_cast(indent, listValue, type: field.type)}');
          }
        }
      });

      indent.write('return $className(');
      for (final NamedType field
          in getFieldsInSerializationOrder(classDefinition)) {
        final String comma =
            getFieldsInSerializationOrder(classDefinition).last == field
                ? ''
                : ', ';
        indent.add('${field.name}$comma');
      }
      indent.addln(')');
    });
  });
}