前言
以前学android的时候就曾经使用过APT在编译时解析注解,然后结合Javapoet生成代码,在flutter端其实也有这种类似的技术,这就是source_gen和code_builder,source_gen负责编译时解析注解,code_builder负责生成代码,本篇文章,就是在讲解如何使用source_gen和code_builder编译时生成代码,code_builder如何使用,请看之前的文章, 本文 github链接
具体步骤
1. 新建flutter package,命名为annotations
这个包专门用来放注解,在这个包中新建一个注解类,如下所示
class ChannelHelp {
final String channelName;
const ChannelHelp(this.channelName); //注解类,构造函数必须是Const的
}
2. 新建flutter package,命名为generate
这个包专门用来解析注解,生成代码,先在pubspec.yaml中依赖上面创建的包annotations,然后再添加依赖source_gen和build_runner,代码如下
name: generate
description: A new Flutter package.
version: 0.0.1
author:
homepage:
environment:
sdk: ">=2.7.0 <3.0.0"
flutter: ">=1.17.0 <2.0.0"
dependencies:
flutter:
sdk: flutter
source_gen: ^0.9.6 #需要包含代码自动库
annotations:
path: ../annotations
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.10.0
flutter:
3.在generate包中新建dart类ChannelHelpGenerator
这个类继承自ChannelHelpGenerator,用于解析ChannelHelp注解,代码如下:
import 'package:analyzer/dart/element/element.dart';
import 'package:annotations/channel_help.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';
import 'package:path/path.dart' as Path;
import 'package:build/build.dart';
class ChannelHelpGenerator extends GeneratorForAnnotation<ChannelHelp> {
static final String channelName = "_MethodChannel";
String className;
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
final emitter = DartEmitter();
if (element is! ClassElement) {
throw InvalidGenerationSourceError('ChannelHelper只能用在类上');
}
className = element.displayName;
var channelName = annotation.peek("channelName").stringValue;
ClassBuilder classBuilder;
var channelHelper = Class((builder) {
classBuilder = builder;
classBuilder.constructors.add(Constructor((constructorBuild) {
constructorBuild.name = "_internal";
}));
classBuilder.name = '${className}Imp';
classBuilder.implements.add(refer(className));
classBuilder.fields.add(Field((fieldBuild) {
fieldBuild.name = "_MethodChannel";
fieldBuild.type = refer("MethodChannel");
fieldBuild.modifier = FieldModifier.final$;
fieldBuild.assignment = Code('MethodChannel("$channelName")');
}));
classBuilder.fields.add(Field((fieldBuild) {
fieldBuild.name = "_$className";
fieldBuild.type = refer("$className");
fieldBuild.static = true;
}));
classBuilder.methods.add(Method((methodBuild) {
methodBuild.name = "getInstance";
methodBuild.returns = refer('$className');
methodBuild.static = true;
methodBuild.body = _generatorSingleInstantBody();
}));
ClassElement classElement = element as ClassElement;
List<MethodElement> methodElements = classElement.methods;
if (methodElements != null && methodElements.length > 0) {
methodElements.forEach((methodElement) {
classBuilder.methods.add(Method((methodBuild) {
methodBuild.name = methodElement.name;
methodBuild.modifier = MethodModifier.async;
methodBuild.returns =
refer("${methodElement.returnType.getDisplayString()}");
methodBuild.annotations.add(TypeReference((build) {
// 给方法添加注解
build.symbol = "override"; //注解类型是override
}));
var parameters = methodElement.parameters;
methodBuild.body = _generatorBody(methodElement, parameters);
}));
});
}
});
String channelHelperStr =
DartFormatter().format('${channelHelper.accept(emitter)}');
return """
part of '${Path.basename(buildStep.inputId.path)}';
$channelHelperStr
""";
}
Code _generatorSingleInstantBody() {
final blocks = <Code>[];
blocks.add(Code("if(_$className == null) {"));
blocks
.add(Code("_$className = ${className}Imp._internal() as $className;"));
blocks.add(Code("}"));
blocks.add(Code("return _$className;"));
return Block.of(blocks);
}
// ignore: missing_return
Code _generatorBody(
MethodElement methodElement, List<ParameterElement> parameters) {
final blocks = <Code>[];
if (parameters == null || parameters.length == 0) {
blocks.add(Code(
"dynamic _result = await $channelName.invokeMethod('${methodElement.name}');"));
}
blocks.add(_generatorResult(methodElement));
return Block.of(blocks);
}
Code _generatorResult(MethodElement methodElement) {
final blocks = <Code>[];
return Block.of(blocks);
}
}
4.在generate包中新建dart文件channel_help_builder
这个包用于加载ChannelHelpGenerator,指定生成的文件后缀,代码如下:
import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart';
import 'channel_help_generator.dart';
Builder nativeCallBuilder(BuilderOptions options) =>
LibraryBuilder(ChannelHelpGenerator(), generatedExtension: '.nc.g.dart');
5.在generate包中新建文件build.yaml
代码如下:
builders:
channel_help_builder:
target: ":annotations" #目标库
import: 'package:generate/channel_help_builder.dart' #build文件
builder_factories: ['nativeCallBuilder']
build_extensions: {'.dart': ['.nc.g.dart']}
auto_apply: dependents #将此Builder应用于包,直接依赖于公开构建起的包,也可以是root_package
build_to: source #输出到注解的目标类的代码同目录中,或者输出转到隐藏的构建缓存,不会发布(cache)
applies_builders: ["source_gen|combining_builder"] #指定是否可以延迟运行构建器
如何使用
1. 在主工程的pubspec.yaml添加依赖annotations,generate,build_runner
代码如下:
name: generate_code
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
annotations:
path: annotations
cupertino_icons: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
generate:
path: generate
build_runner: ^1.4.0
flutter:
uses-material-design: true
2. 新建ChannelTest文件,添加ChannelHelp注解
代码如下
import 'package:annotations/channel_help.dart';
import 'package:flutter/services.dart';
part 'channel_test.nc.g.dart';
@ChannelHelp('test')
abstract class ChannelTest {
void test();
}
3.执行指令,如下
flutter packages pub run build_runner build
4.等待指令执行完成即可看见编译生成的代码
代码如下:
part of 'channel_test.dart';
class ChannelTestImp implements ChannelTest {
ChannelTestImp._internal();
final MethodChannel _MethodChannel = MethodChannel("test");
static ChannelTest _ChannelTest;
static ChannelTest getInstance() {
if (_ChannelTest == null) {
_ChannelTest = ChannelTestImp._internal() as ChannelTest;
}
return _ChannelTest;
}
@override
void test() async {
dynamic _result = await _MethodChannel.invokeMethod('test');
}
}
QQ交流群
群号码:770892444