这篇文章里面有对build_runner 的详细介绍 》 https://juejin.cn/post/6844903878392053774
1. 新建一个plugin,名字叫code_generate
2. 在code_generate
项目下
pubspec.yaml文件中添加source_gen
dependencies:
flutter:
sdk: flutter
source_gen: '>=0.8.0'
创建builder.dart文件
import 'package:code_generate/api_generator.dart';
import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart';
Builder apiServiceBuilder(BuilderOptions options) => LibraryBuilder(ApiServiceGenerator());
创建api_service.dart文件
const Object apiService = ApiService();
class ApiService {
final String method;
const ApiService({this.method = ""});
}
创建api_generator.dart文件
import 'package:analyzer/dart/element/element.dart';
import 'package:code_generate/api_service.dart';
import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart';
class ApiServiceGenerator extends GeneratorForAnnotation<ApiService> {
@override
generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep) {
// String className = element.displayName;
// String path = buildStep.inputId.path;
// String name = annotation.peek('name').stringValue;
// $path $name $className
return '''
///我是ApiServiceGenerator 》》
''';
}
}
3.新建build.yaml文件
targets:
$default:
builders:
mark_builder:
enabled: true
builders:
mark_builder:
import: 'package:code_generate/builder.dart'
builder_factories: ['apiServiceBuilder']
build_extensions: { '.dart': ['.dsm.dart'] }
auto_apply: root_package
build_to: source
4. 在主项目中的pubspec.yaml文件中引入这个插件并加入build_runner
库
dependencies:
code_generate:
path: code_generate/
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: '>=0.9.1' #需要引用该库
在使用的时候
@apiService
abstract class MyService {
void requestLogin(String params);
}
运行
flutter packages pub run build_runner build
网友评论