writeClassDecode method

  1. @override
void writeClassDecode(
  1. DartOptions 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(
  DartOptions generatorOptions,
  Root root,
  Indent indent,
  Class classDefinition, {
  required String dartPackageName,
}) {
  void writeValueDecode(NamedType field, int index) {
    final String resultAt = 'result[$index]';
    final String castCallPrefix = field.type.isNullable ? '?' : '!';
    final String genericType = _makeGenericTypeArguments(field.type);
    final String castCall = _makeGenericCastCall(field.type);
    final String nullableTag = field.type.isNullable ? '?' : '';
    if (field.type.isEnum) {
      final String nonNullValue =
          '${field.type.baseName}.values[$resultAt! as int]';
      if (field.type.isNullable) {
        indent.format('''
$resultAt != null
\t\t? $nonNullValue
\t\t: null''', leadingSpace: false, trailingNewline: false);
      } else {
        indent.add(nonNullValue);
      }
    } else if (field.type.typeArguments.isNotEmpty) {
      indent.add(
        '($resultAt as $genericType?)$castCallPrefix$castCall',
      );
    } else {
      final String castCallForcePrefix = field.type.isNullable ? '' : '!';
      final String castString = field.type.baseName == 'Object'
          ? ''
          : ' as $genericType$nullableTag';

      indent.add(
        '$resultAt$castCallForcePrefix$castString',
      );
    }
  }

  indent.write(
    'static ${classDefinition.name} decode(Object result) ',
  );
  indent.addScoped('{', '}', () {
    indent.writeln('result as List<Object?>;');
    indent.write('return ${classDefinition.name}');
    indent.addScoped('(', ');', () {
      enumerate(getFieldsInSerializationOrder(classDefinition),
          (int index, final NamedType field) {
        indent.write('${field.name}: ');
        writeValueDecode(field, index);
        indent.addln(',');
      });
    });
  });
}