Flutter注解爬虫插件annotation_crawler的使用
Flutter注解爬虫插件annotation_crawler的使用
annotation_crawler
插件可以帮助你在特定作用域内找到带有注解的声明。以下是一些主要的函数:
函数简介
// 返回一个包含每个顶级声明的AnnotatedDeclaration列表,这些声明具有Foo注解。
annotatedDeclarations(Foo);
// 做同样的事情,但仅限于SomeClass内的声明
annotatedDeclarations(Foo, on: SomeClass);
// 返回一个包含每个具有Foo注解的类的ClassMirror列表。
findClasses(Foo);
// 返回一个包含SomeClass上每个具有Foo注解的方法的MethodMirror列表。
findMethodsOnClass(SomeClass, Foo);
// 返回一个包含someObject上每个具有Foo注解的方法的MethodMirror列表。
findMethodsOnInstance(someObject, Foo);
示例代码
以下是使用annotation_crawler
插件的一个完整示例。
import 'dart:mirrors';
import 'package:annotation_crawler/annotation_crawler.dart';
// 定义一个名为Author的注解
class Author {
final String name;
const Author(this.name);
}
// 定义一个名为Scene的注解
class Scene {
final int act;
final int scene;
const Scene({required this.act, required this.scene});
}
// 定义一个抽象类Play
abstract class Play {
final String name;
Play(this.name);
void perform();
}
// 定义一个继承自Play的类MajestyPlay,并添加注解
[@Author](/user/Author)('Arthur Miller')
class MajestyPlay extends Play {
MajestyPlay() : super('Her majesty\'s Theater');
[@override](/user/override)
perform() {
performAct1Scene1();
performAct1Scene2();
performAct2Scene1();
}
[@Scene](/user/Scene)(act: 1, scene: 1)
void performAct1Scene1() => print('Performing play "$name" act 1 scene 1.');
[@Scene](/user/Scene)(act: 1, scene: 2)
void performAct1Scene2() => print('Performing play "$name" act 1 scene 2.');
[@Scene](/user/Scene)(act: 2, scene: 1)
void performAct2Scene1() => print('Performing play "$name" act 2 scene 1.');
}
void main() {
// 执行所有由Arthur Miller编写的剧目
annotatedDeclarations(Author)
.where((decl) =>
decl.declaration is ClassMirror &&
decl.annotation == const Author("Arthur Miller"))
.forEach((decl) {
final playClass = decl.declaration as ClassMirror;
final play = playClass.newInstance(const Symbol(''), []).reflectee as Play;
play.perform();
});
print('现在只播放第二幕第一场:');
final majestyPlay = MajestyPlay();
final declaration = annotatedDeclarations(Scene, on: majestyPlay.runtimeType)
.singleWhere((decl) {
final Scene scene = decl.annotation as Scene;
return scene.act == 2 && scene.scene == 1;
});
/// 在给定对象上调用找到的方法。
reflect(majestyPlay).invoke(declaration.declaration.simpleName, []);
}
更多关于Flutter注解爬虫插件annotation_crawler的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复