generateForAnnotatedElement method

  1. @override
FutureOr<String> generateForAnnotatedElement(
  1. Element element,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)

Main entry point for CherryPick field injection code generation.

  • Only triggers for classes marked with @injectable().
  • Throws an error if used on non-class elements.
  • Scans all fields marked with @inject() and gathers qualifiers (if any).
  • Generates Dart code for a mixin that injects all dependencies into the target class instance.

Returns the Dart code as a String defining the new mixin.

Example input (user code):

@injectable()
class UserBloc with _$UserBloc {
  @inject() late final AuthRepository authRepository;
}

Example output (generated):

mixin _$UserBloc {
  void _inject(UserBloc instance) {
    instance.authRepository = CherryPick.openRootScope().resolve<AuthRepository>();
  }
}

Implementation

@override
FutureOr<String> generateForAnnotatedElement(
  Element element,
  ConstantReader annotation,
  BuildStep buildStep,
) {
  if (element is! ClassElement) {
    throw InvalidGenerationSourceError(
      '@injectable() can only be applied to classes.',
      element: element,
    );
  }

  final classElement = element;
  final className = classElement.name;
  final mixinName = '_\$$className';

  final buffer = StringBuffer()
    ..writeln('mixin $mixinName {')
    ..writeln('  void _inject($className instance) {');

  // Collect and process all @inject fields
  final injectFields =
      classElement.fields.where(_isInjectField).map(_parseInjectField);

  for (final parsedField in injectFields) {
    buffer.writeln(_generateInjectionLine(parsedField));
  }

  buffer
    ..writeln('  }')
    ..writeln('}');

  return buffer.toString();
}