InjectGenerator class

CherryPick DI field injector generator for codegen.

Analyzes all Dart classes marked with @injectable() and generates a mixin (for example, _$ProfileScreen) which contains the _inject method. This method will assign all fields annotated with @inject() using the CherryPick DI container. Extra annotation qualifiers such as @named and @scope are respected for each field. Nullable fields and Future/injectable async dependencies are also supported automatically.


Example usage in a project:

import 'package:cherrypick_annotations/cherrypick_annotations.dart';

@injectable()
class MyScreen with _$MyScreen {
  @inject()
  late final Logger logger;

  @inject()
  @named('test')
  late final HttpClient client;

  @inject()
  Future<Analytics>? analytics;
}

After running build_runner, this mixin will be auto-generated:

mixin _$MyScreen {
  void _inject(MyScreen instance) {
    instance.logger = CherryPick.openRootScope().resolve<Logger>();
    instance.client = CherryPick.openRootScope().resolve<HttpClient>(named: 'test');
    instance.analytics = CherryPick.openRootScope().tryResolveAsync<Analytics>(); // nullable async inject
  }
}

You may use the mixin (e.g., myScreen._inject(myScreen)) or expose your own public helper for instance field injection.

Supported scenarios:

  • Ordinary injectable fields: resolve<T>().
  • Named qualifiers: resolve<T>(named: ...).
  • Scoping: CherryPick.openScope(scopeName: ...).resolve<T>().
  • Nullable/incomplete fields: tryResolve/tryResolveAsync.
  • Async dependencies: Future<T>/resolveAsync<T>().

See also:

  • @inject
  • @injectable

Constructors

InjectGenerator.new()
const

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
throwOnUnresolved bool
finalinherited
typeChecker → TypeChecker
no setterinherited

Methods

generate(LibraryReader library, BuildStep buildStep) FutureOr<String>
Generates Dart code for an input Dart library.
inherited
generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep) FutureOr<String>
Main entry point for CherryPick field injection code generation.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited