generateForAnnotatedElement method

  1. @override
FutureOr<String> generateForAnnotatedElement (
  1. Element element,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)
override

Implement to return source code to generate for element.

This method is invoked based on finding elements annotated with an instance of T. The annotation is provided as a ConstantReader.

Supported return values include a single String or multiple String instances within an Iterable or Stream. It is also valid to return a Future of String, Iterable, or Stream.

Implementations should return null when no content is generated. Empty or whitespace-only String instances are also ignored.

Implementation

@override
FutureOr<String> generateForAnnotatedElement(Element element,
    ConstantReader annotation,
    BuildStep buildStep,) {
  final visitor = _ModelVisitor();
  element.visitChildren(visitor);

  final className = visitor.className;
  final methodInput = [];
  final constructorInput = [];

  for (var key in visitor.fields.keys) {
    FieldElement field = visitor.fields[key];

    if (_ignoreFieldElement(field)) {
      continue;
    }

    methodInput.add(
      '    ${field.type} ${field.name},',
    );

    constructorInput.add(
      '      ${field.name}: ${field.name} ?? this.${field.name},',
    );
  }

  final buffer = StringBuffer();

  buffer.writeln(
    'extension  \$${className}CopyWith on $className {'
        '  $className copyWith({${methodInput.join("\r\n")}}) {'
        '    return $className(${constructorInput.join("\r\n")});'
        '  }'
        '}',
  );

  return buffer.toString();
}