buildCopyWithSnippet function

String? buildCopyWithSnippet(
  1. ClassDeclaration classDecl
)

Builds a copyWith(...) snippet for the class based on the best constructor. Returns null if no suitable constructor/fields found.

Implementation

String? buildCopyWithSnippet(ClassDeclaration classDecl) {
  final className = getClassName(classDecl);
  final constructorFields = getClassFields(classDecl, constructorOnly: true);
  if (constructorFields.isEmpty) {
    return null;
  }

  final positionalFields = constructorFields.where((f) => !f.isNamed).toList();
  final namedFields = constructorFields.where((f) => f.isNamed).toList();

  final params = constructorFields
      .map((f) {
        if (f.isNullable) {
          return '({${f.type}? value})? ${f.name}';
        } else {
          return '({${f.type} value})? ${f.name}';
        }
      })
      .join(', ');

  final positionalArgs = positionalFields
      .map((f) => '${f.name} == null ? this.${f.name} : ${f.name}.value')
      .join(', ');

  final namedArgs = namedFields
      .map(
        (f) =>
            '${f.name}: ${f.name} == null ? this.${f.name} : ${f.name}.value',
      )
      .join(', ');

  final constructorArgs = [
    if (positionalArgs.isNotEmpty) positionalArgs,
    if (namedArgs.isNotEmpty) namedArgs,
  ].join(', ');

  return '''

  $className copyWith({$params}) {
    return $className($constructorArgs);
  }
''';
}