1, 定義注解.
2谅河,定義生成器
3咱旱,定義builder
4,build入口配置
5绷耍,編寫源文件.dart吐限,使用我們自定義的注解
定義一個(gè)注解,注解的參數(shù)褂始,會(huì)傳遞到給生成器
6诸典,執(zhí)行build命令,生成目標(biāo)文件.g.dart
整體過程如下圖:
1, 定義注解
second_annoation.dart
class SecondAnnoation {
final String content;
const SecondAnnoation(this.content);
}
2崎苗, 定義生成器
就是把注解帶過來的參數(shù)狐粱,經(jīng)過處理,返回新的代碼文本
second_gennerator.dart
import 'package:demo/tools/resource/second_annoation.dart';
import 'package:source_gen/source_gen.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
class SecondGenerator extends GeneratorForAnnotation<SecondAnnoation> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
var content = annotation.peek('content').stringValue;
String _codeContent = '\n\t\t\t\tstatic const $content = \'valueA ~~~\';';
return 'class HelloClass{\n'
' HelloClass._();\n'
' $_codeContent\n'
'}';
}
}
3胆数,定義builder
就是用來綁定的肌蜻, build.yaml入口執(zhí)行那個(gè)生成器,一一對應(yīng)
builder.dart
import 'package:build/build.dart';
import 'package:demo/tools/resource/second_gennerator.dart';
import 'package:source_gen/source_gen.dart';
Builder mybuilder(BuilderOptions options) =>
SharedPartBuilder([SecondGenerator()], "resource_metadata_other");
4必尼,build入口配置
build.yaml
targets:
$default:
builders:
demo|resource_metadata_other:
enabled: true
builders:
resource_metadata_other:
import: "package:demo/tools/mybuilderplayground/builder.dart"
builder_factories: [ "mybuilder"]
build_extensions: {".dart": [".g.part"]}
auto_apply: dependents
build_to: cache
applies_builders: ["source_gen|combining_builder"]
5蒋搜,編寫源文件.dart,使用我們自定義的注解
定義一個(gè)注解判莉,注解的參數(shù)齿诞,會(huì)傳遞到給生成器
import 'package:demo/tools/resource/second_annoation.dart';
part 'second_from.g.dart';
@SecondAnnoation('helloworld')
class R {}
6,執(zhí)行build命令骂租,生成目標(biāo)文件.g.dart
# 如果存在新文件需要更新祷杈,建議先執(zhí)行清除命令:
flutter packages pub run build_runner clean
# 然后執(zhí)行下列命令重新生成相應(yīng)文件:
flutter packages pub run build_runner build --delete-conflicting-outputs
#flutter packages pub run build_runner watch
生成的.g.dart如下了
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'second_from.dart';
// **************************************************************************
// SecondGenerator
// **************************************************************************
class HelloClass {
HelloClass._();
static const helloworld = 'valueA ~~~';
}