我正在使用 为 Dart 编写代码生成器build_runner
,但我的构建器不会被调用以在字段中进行注释,尽管它确实适用于类中的注释。
是否也可以在字段(或在任何地方)调用注释生成器?
例如,为以下文件调用构建器:
import 'package:my_annotation/my_annotation.dart';
part 'example.g.dart';
@MyAnnotation()
class Fruit {
int number;
}
但不适用于这个:
import 'package:my_annotation/my_annotation.dart';
part 'example.g.dart';
class Fruit {
@MyAnnotation()
int number;
}
这是注解的定义:
class MyAnnotation {
const MyAnnotation();
}
这就是生成器的定义方式。目前,它只是在被调用时中止,从而导致打印错误消息。
library my_annotation_generator;
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:my_annotation/my_annotation.dart';
import 'package:source_gen/source_gen.dart';
Builder generateAnnotation(BuilderOptions options) =>
SharedPartBuilder([MyAnnotationGenerator()], 'my_annotation');
class MyAnnotationGenerator extends GeneratorForAnnotation<MyAnnotation> {
@override
generateForAnnotatedElement(Element element, ConstantReader annotation, _) {
throw CodeGenError('Generating code for annotation is not implemented yet.');
}
这是build.yaml
配置:
targets:
$default:
builders:
my_annotation_generator|my_annotation:
enabled: true
builders:
my_annotation:
target: ":my_annotation_generator"
import: "package:my_annotation/my_annotation.dart"
builder_factories: ["generateAnnotation"]
build_extensions: { ".dart": [".my_annotation.g.part"] }
auto_apply: dependents
build_to: cache
applies_builders: ["source_gen|combining_builder"]