generateForAnnotatedElement method

  1. @override
dynamic generateForAnnotatedElement(
  1. Element element,
  2. ConstantReader annotation,
  3. 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
generateForAnnotatedElement(Element element, ConstantReader annotation,
    BuildStep buildStep) {
  _extensionClsName = annotation.peek('className').stringValue;
  _extensionOnClsName = annotation.peek('on').stringValue;
  _key = annotation.peek('key').stringValue;
  if (ApiGenerator.functions.isEmpty && _key.isEmpty) {
    /// 单个注解类生成相应文件,不合并
    return null;
  }
  print('ApiExtensionGenerator _extensionClsName[$_extensionClsName]\n');

  Template tpl = Template(ApiUtilTpl.tpl);
  String content = tpl.renderString({
    'imports': _key.isEmpty ? ApiGenerator.imports : Collector.inst.importsMap[_key],
    'className': _extensionClsName,
    'targetClassName': _extensionOnClsName,
    'functions': _key.isEmpty ? ApiGenerator.functions : Collector.inst.functionsMap[_key],
  });

  if (_key.isNotEmpty) {
    Collector.inst.importsMap[_key]?.clear();
    Collector.inst.importsMap.remove(_key);
    Collector.inst.functionsMap[_key]?.clear();
    Collector.inst.functionsMap.remove(_key);
    Collector.inst.importMap[_key]?.clear();
    Collector.inst.importMap.remove(_key);
  }

  print('Collector.inst.functionsMap size : ${Collector.inst.functionsMap.length}\n');

  return content;
}