个人博客:
http://www.milovetingting.cn

Typedefs

类型别名是引用某一类型的简便方法,因为其使用关键字 typedef,因此通常被称作 typedef。下面是一个使用 IntList 来声明和使用类型别名的例子:

1
2
typedef IntList = List<int>;
IntList il = [1, 2, 3];

类型别名可以有类型参数:

1
2
3
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.

针对函数,在大多数情况下,我们推荐使用 内联函数类型 替代 typedefs。然而,函数的 typedefs 仍然是有用的:

1
2
3
4
5
6
7
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!
}

元数据

使用元数据可以为代码增加一些额外的信息。元数据注解以 @ 开头,其后紧跟一个编译时常量(比如 deprecated)或者调用一个常量构造函数。

Dart 中有两个注解是所有代码都可以使用的: @deprecated@Deprecated@override。你可以查阅 扩展一个类 获取有关 @override 的使用示例。下面是使用 @deprecated 的示例:

1
2
3
4
5
6
7
8
9
10
11
class Television {
/// Use [turnOn] to turn the power on instead.
@Deprecated('Use turnOn instead')
void activate() {
turnOn();
}

/// Turns the TV's power on.
void turnOn() {...}
// ···
}

可以自定义元数据注解。下面的示例定义了一个带有两个参数的 @todo 注解:

1
2
3
4
5
6
7
8
library todo;

class Todo {
final String who;
final String what;

const Todo(this.who, this.what);
}

使用 @Todo 注解的示例:

1
2
3
4
5
6
import 'todo.dart';

@Todo('seth', 'make this do something')
void doSomething() {
print('do something');
}

元数据可以在 library、class、typedef、type parameter、 constructor、factory、function、field、parameter 或者 variable 声明之前使用,也可以在 import 或 export 之前使用。可使用反射在运行时获取元数据信息。

注释

Dart 支持单行注释、多行注释和文档注释。

单行注释

单行注释以 // 开始。所有在 // 和该行结尾之间的内容均被编译器忽略。

1
2
3
4
void main() {
// TODO: refactor into an AbstractLlamaGreetingFactory?
print('Welcome to my Llama farm!');
}

多行注释

多行注释以 /* 开始,以 */ 结尾。所有在 /**/ 之间的内容均被编译器忽略(不会忽略文档注释),多行注释可以嵌套。

1
2
3
4
5
6
7
8
9
10
void main() {
/*
* This is a lot of work. Consider raising chickens.

Llama larry = Llama();
larry.feed();
larry.exercise();
larry.clean();
*/
}

文档注释

文档注释可以是多行注释,也可以是单行注释,文档注释以 /// 或者 /** 开始。在连续行上使用 /// 与多行文档注释具有相同的效果。

在文档注释中,除非用中括号括起来,否则分析器会忽略所有文本。使用中括号可以引用类、方法、字段、顶级变量、函数和参数。括号中的符号会在已记录的程序元素的词法域中进行解析。

下面是一个引用其他类和成员的文档注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// A domesticated South American camelid (Lama glama).
///
/// Andean cultures have used llamas as meat and pack
/// animals since pre-Hispanic times.
///
/// Just like any other animal, llamas need to eat,
/// so don't forget to [feed] them some [Food].
class Llama {
String? name;

/// Feeds your llama [food].
///
/// The typical llama eats one bale of hay per week.
void feed(Food food) {
// ...
}

/// Exercises your llama with an [activity] for
/// [timeLimit] minutes.
void exercise(Activity activity, int timeLimit) {
// ...
}
}

在生成的文档中,[feed] 会成为一个链接,指向 feed 方法的文档, [Food] 会成为一个链接,指向 Food 类的 API 文档。

解析 Dart 代码并生成 HTML 文档,可以使用 Dart 的文档生成工具 dart doc。关于生成文档的示例,请参考 Dart API documentation 查看关于文档结构的建议,请参考文档: Guidelines for Dart Doc Comments.