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
dynamic generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep) async {
  final generateForDir = annotation.read('generateForDir').listValue.map((e) => e.toStringValue());

  var targetFile = element.source!.uri;
  var preferRelativeImports = (annotation.peek("preferRelativeImports")?.boolValue ?? true == true);
  var isMicroPackageRoot = annotation.instanceOf(_microPackageRootInit);


  final dirPattern = generateForDir.length > 1 ? '{${generateForDir.join(',')}}' : '${generateForDir.first}';
  final injectableConfigFiles = Glob("$dirPattern/**.injectable.json");

  final jsonData = <Map>[];
  await for (final id in buildStep.findAssets(injectableConfigFiles)) {
    final json = jsonDecode(await buildStep.readAsString(id));
    jsonData.addAll([...json]);
  }

  final deps = <DependencyConfig>[];
  jsonData.forEach((json) => deps.add(DependencyConfig.fromJson(json as Map<String, dynamic>)));

  final initializerName = annotation.read('initializerName').stringValue;
  final asExtension = annotation.read('asExtension').boolValue;

  _reportMissingDependencies(deps, targetFile);
  _validateDuplicateDependencies(deps);
  return ConfigCodeGenerator(
    deps,
    targetFile: preferRelativeImports ? targetFile : null,
    initializerName: initializerName,
    asExtension: asExtension,
    isMicroPackageRoot: isMicroPackageRoot
  ).generate();
}