generateForAnnotatedElement method
Future<void>
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
Future<void> generateForAnnotatedElement(
Element element,
ConstantReader annotation,
BuildStep buildStep,
) async {
try {
final routing = Routing(
varName: annotation.read('varName').stringValue,
generateFor: annotation.read('generateFor').listValue.map((e) {
return e.toStringValue()!;
}).toList(),
);
final routers = await _findRouters(buildStep, routing.generateFor.map(Glob.new)).toList();
final varName = '\$${routing.varName}';
final mountedRouters = routers.map((e) {
return "..mount('${e.annotation.prefix}', ${e.element.name}().router)";
});
final importRouters = routers.map((e) => "import '${e.element.library.identifier}';");
final result = "import 'package:shelf_router/shelf_router.dart';\n"
'${importRouters.map((e) => '$e\n').join()}'
'\n'
'final $varName = Router()${mountedRouters.map((e) => '\n $e').join('')};';
await buildStep.writeAsString(buildStep.allowedOutputs.single, result);
} catch (error, stackTrace) {
log.severe('$error\n$stackTrace');
}
}