个人博客:
http://www.milovetingting.cn
dev_dependencies:
source_gen: ^1.2.6
build_runner: '>2.3.0 <4.0.0'
import 'package:meta/meta_meta.dart';
///定义注解
@Target({TargetKind.classType})
class JsonGeneratorTest {
final String name;
final int age;
const JsonGeneratorTest(this.name, this.age);
}
import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';
import 'generator.dart';
/// 注解解析
class TestGenerator extends GeneratorForAnnotation<JsonGeneratorTest> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
_analyseBuildStep(buildStep);
_analyseAnnotation(annotation);
_analyseElement(element);
return template("_\$${element.name}", "Gen Code");
}
void _analyseBuildStep(BuildStep buildStep) {
print("buildStep:${buildStep.inputId.toString()}\n");
}
void _analyseAnnotation(ConstantReader annotation) {
print("params: ${annotation.read("name")}\n");
print("params: ${annotation.read("age")}\n");
}
void _analyseElement(Element element) {
print("ElementKind:${element.kind.name}\n");
switch (element.kind) {
case ElementKind.CLASS:
_analyseElementForClass(element);
break;
case ElementKind.FUNCTION:
_analyseElementForMethod(element);
break;
default:
break;
}
}
void _analyseElementForClass(Element element) {
var e = element as ClassElement;
e.fields.forEach((element) {
print("字段:${element.declaration}\n");
});
e.methods.forEach((element) {
print("方法:${element.declaration}");
});
}
void _analyseElementForMethod(Element element) {
print(
"方法名称:${element.name},方法参数:${(element as FunctionElement).parameters[0].declaration}");
}
template(String className, String content) {
return """
class ${className}{
/**
$content
*/
}
""";
}
}
import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart' as build;
import 'generator_impl.dart';
///配置builder
build.Builder testBuilder(build.BuilderOptions options) =>
PartBuilder([TestGenerator()], ".gen.dart");
在根目录下新增build.yaml
builders:
testBuilder:
import: "package:flutter_demo/generator/test_builder.dart"
builder_factories: ["testBuilder"]
build_extensions: {".dart": [".g.part"]}
auto_apply: root_package
build_to: source
import 'package:flutter_demo/generator/generator.dart';
///包含foo.gen.dart文件
part 'foo.gen.dart';
///使用注解
@JsonGeneratorTest("张三", 18)
class Foo {
String name;
int age;
Foo(this.name, this.age);
}
flutter pub run build_runner build --delete-conflicting-outputs
–delete-conflicting-outputs:删除冲突的文件,可以删除原来生成的文件
执行命令后,会在Foo.dart
同目录下生成foo.gen.dart
文件