generateForAnnotatedElement method

  1. @override
FutureOr<String> 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
FutureOr<String> generateForAnnotatedElement(
    Element element, ConstantReader annotation, BuildStep buildStep) async {
  if (element is! ClassElement) {
    final name = element.name;
    throw InvalidGenerationSourceError('Generator cannot target `$name`.',
        todo: 'Remove the SheetLocalization annotation from `$name`.',
        element: element);
  }

  if (!element.name.endsWith('Delegate')) {
    final name = element.name;
    throw InvalidGenerationSourceError(
        'Generator for target `$name` should have a name that ends with `Delegate`.',
        todo:
            'Refactor the class name `$name` for a name ending with `Delegate` (example: `${name}Delegate`).',
        element: element);
  }

  /*
  element.allSupertypes.firstWhere(
    (x) =>
        x.getDisplayString(withNullability: false) == 'LocalizationsDelegate',
    orElse: () => throw InvalidGenerationSourceError(
      'Supertype aren\'t valid : [${element.allSupertypes.map((x) => x.getDisplayString(withNullability: false)).join(', ')}].',
      todo:
          'Define only one supertype of type LocalizationsDelegate<LOCALIZATION_CLASS_NAME>.',
      element: element,
    ),
  );*/
  final name = '${element.name.replaceAll('Delegate', '')}Data';
  final docId = annotation.objectValue.getField('docId')!.toStringValue();
  final sheetId = annotation.objectValue.getField('sheetId')!.toStringValue();
  var localizations = await _downloadGoogleSheet(
    docId!,
    sheetId!,
    name,
  );
  final builder = DartLocalizationBuilder();
  final code = StringBuffer();
  code.writeln(builder.build(localizations));
  return code.toString();
}