2021-04-15 flutter实现自定义注解&注解生成代码

1, 定义注解.
2,定义生成器
3,定义builder
4,build入口配置
5,编写源文件.dart,使用我们自定义的注解
定义一个注解,注解的参数,会传递到给生成器
6,执行build命令,生成目标文件.g.dart

整体过程如下图:


2021-04-15 flutter实现自定义注解&注解生成代码_第1张图片
image.png

1, 定义注解

second_annoation.dart

class SecondAnnoation {
  final String content;

  const SecondAnnoation(this.content);
}

2, 定义生成器

就是把注解带过来的参数,经过处理,返回新的代码文本

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 {
  @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入口执行那个生成器,一一对应

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,使用我们自定义的注解

定义一个注解,注解的参数,会传递到给生成器

import 'package:demo/tools/resource/second_annoation.dart';

part 'second_from.g.dart';

@SecondAnnoation('helloworld')
class R {}

6,执行build命令,生成目标文件.g.dart

# 如果存在新文件需要更新,建议先执行清除命令:
flutter packages pub run build_runner clean
# 然后执行下列命令重新生成相应文件:
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 ~~~';
}

你可能感兴趣的:(2021-04-15 flutter实现自定义注解&注解生成代码)