MethodCopyWithBuilder function

Method MethodCopyWithBuilder({
  1. required String className,
  2. required List<FieldInfo> fields,
})

Implementation

Method MethodCopyWithBuilder({
  required String className,
  required List<FieldInfo> fields,
}) {
  return Method((builder) {
    builder.docs.addAll([
      '/// Creates a copy of this [$className] but with the given fields',
      '/// replaced with the new values.',
    ]);
    builder.annotations.add(refer('override'));
    builder.name = 'copyWith';
    builder.returns = refer(className);
    builder.optionalParameters.addAll(fields.methodParams);
    builder.body = Code('''
        return $className(
          ${fields.map((field) => '${field.name}: ${field.name} ?? this.${field.name}').join(', ')},
        );
      ''');
  });
}