generateForAnnotatedElement method
dynamic
generateForAnnotatedElement(
- Element element,
- ConstantReader annotation,
- BuildStep buildStep
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
dynamic generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
final config = readConfig(annotation, element);
final typeList = config['forClasses'] as List<DartObject>;
final build = <Spec>[];
final classesToGenerate =
typeList.map((type) => type.toTypeValue()!.element!).toList();
for (final clazz in classesToGenerate) {
if (clazz is! ClassElement) {
throw InvalidGenerationSourceError(
'${element.displayName} is not a class and a generator cannot be created for this',
element: element,
todo: 'Only add classes to the generatable classes');
}
build.add(buildClass(clazz));
}
build.add(buildInit(classesToGenerate));
final lib = generateLibrary(build, classesToGenerate);
final emitter = DartEmitter(
allocator: Allocator.simplePrefixing(),
orderDirectives: true,
useNullSafetySyntax: true,
);
return '${lib.accept(emitter)}';
}