Typedef
可以理解成Kotlin中typealias
的函数限定版,只能用来对函数定义别名。
typedef GestureTapDownCallback = void Function(TapDownDetails details);
定义还可以携带泛型
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!
}
注解
注解在Dart中称作元数据(Metadata)。
Dart的注解是小写字母开头,Java中是大写。
Dart内置的注解参考annoations.dart , 其中最常用有@deprecated
与@override
等,例如:
class Television {
/// _Deprecated: Use [turnOn] instead._
@deprecated
void activate() {
turnOn();
}
/// Turns the TV's power on.
void turnOn() {...}
}
可以通过常量构造函数类
自定义注解
import 'dart:mirrors';
class Todo {
final String comment;
const Todo(this.comment);
}
@Todo("构造函数的参数")
class Hoge {}
main() {
final h = Hoge();
final mirror = reflectClass(Hoge);
final todoRef = mirror.metadata.first;
print(todoRef.reflectee.comment);
}
在反射中可以获取注解的变量。