generate method

  1. @override
String generate(
  1. List<ClassMember> members
)

Implementation

@override
String generate(List<ClassMember> members) {
  var serialize = '';

  for (var member in members) {
    if (!(member is FieldDeclaration)) continue;

    final isNullable = member.fields.type.toString().contains('?');
    final dot = isNullable ? '?.' : '.';
    final type = member.fields.type
        .toString()
        .replaceAll('\$', '')
        .replaceAll('?', '');
    final name = member.fields.variables.first.name.lexeme;

    if (primitives.contains(type)) {
      serialize += "'$name': $name,";
    } else if (type == 'Type') {
      serialize += "'$name': 'Type<$name>',";
    } else if (type == 'double') {
      serialize += "'$name': $name,";
    } else if (type == 'Decimal') {
      serialize += "'$name': $name${dot}toDouble(),";
    } else if (enums.contains(type)) {
      serialize += "'$name': $name${dot}value,";
    } else if (type.contains('Map<')) {
      var types = type
          .substring(4, type.lastIndexOf('>'))
          .split(',')
          .map((e) => e.trim())
          .toList();

      var type1 = '?.serialize()';
      var type2 = '?.serialize()';

      if (primitives.contains(types[0].trim())) type1 = '';
      if (primitives.contains(types[1].trim())) type2 = '';

      if (types[0].startsWith('List<')) {
        var listPrimitive =
            types[0].replaceAll('List<', '').replaceAll('>', '');
        if (primitives.contains(listPrimitive)) {
          type1 = '';
        }
      }

      if (types[1].startsWith('List<')) {
        var listPrimitive =
            types[1].replaceAll('List<', '').replaceAll('>', '');
        if (primitives.contains(listPrimitive)) {
          type2 = '';
        }
      }

      if (type1 == '' && type2 == '') {
        serialize += "'$name': $name,";
      } else {
        serialize +=
            "'$name': $name${dot}map((dynamic k, dynamic v) => MapEntry(k$type1, v$type2)),";
      }
    } else if (type == 'Map') {
      serialize += "'$name': $name,";
    } else if (type.contains('List<')) {
      final dotMap = isNullable ? '?.map' : '.map';
      final listPrimitive = type.replaceAll('List<', '').replaceAll('>', '');

      if (primitives.contains(listPrimitive)) {
        serialize += "'$name': $name,";
      } else if (enums.contains(listPrimitive)) {
        serialize +=
            "'$name': $name$dotMap((dynamic i) => i?.value).toList(),";
      } else {
        serialize +=
            "'$name': $name$dotMap((dynamic i) => i?.serialize()).toList(),";
      }
    } else {
      if (isNullable) {
        serialize += "'$name': $name?.serialize(),";
      } else {
        serialize += "'$name': $name.serialize(),";
      }
    }
  }

  return 'Map<String, dynamic> serialize() => {$serialize};';
}