flutter 使用source_gen和code_builder編譯時生成程式碼

陳平大將發表於2021-03-31

前言

以前學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

相關文章