基本语法

语言特性

  • 一切皆对象。
  • Dart没有 public、protected、private 等关键字,如果一个标识符以 _开头则表示私有。
  • 标识符以小写字母或下划线_开头,后面跟着字符和数字的任意组合。

Read More

接口

定义

使用implements关键字来使用接口,实现类必须实现接口中所有的方法。Dart中没有interface关键字,implements后可以接任意类。implements后面可以跟多个类,使用逗号隔开。

每一个类都隐式地定义了一个接口并实现了该接口,这个接口包含所有这个类的实例成员以及这个类所实现的其它接口。

Example

1
2


Mixin

定义

字面意思理解成混合,它可以混合多个类,达到多继承的效果。

当继承多个mixin,mixin内重写覆盖了同一个方法,则调用方法时会命中最后with的mixin对应的方法。如果需要链路调用,使用super。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
mixin A {
test() {
print('A');
}
}
mixin B {
test() {
print('B');
}
}

class C {
test() {
print('C');
}
}
/// 使用with关键字,后跟一个或多个mixin或者普通类
class D extends C with A, B {}

class E extends C with B, A {}


main() {
D d = D();
d.test();

E e = E();
e.test();
}

output:
B
A


class D extends C with A, B {}
可以理解成:
class CA = C with A;
class CAB = CA with B;
class D extends CAS {}
所以输出结果为B

class E extends C with B, A {}
class CB = C with B;
class CBA = CB with A;
class E extends CBA;
所以输出结果为A

on

on关键字用来限制mixin的使用,这个mixin只能使用在on指定的类或者其子类。

Read More

Map

遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 使用 forEach 进行遍历
president.forEach( (key, value){
print("forEach 遍历 : $key : $value");
} );

// 2 . 通过 for 循环遍历 Map 集合
// 调用 Map 对象的 keys 成员 , 返回一个由 键 Key 组成的数组
for (var key in president.keys){
print("for 循环遍历 : Key : $key , Value : ${president[key]}");
}

// 3 . 使用 map 方法进行遍历
// 遍历过程中生成新的 Map 集合
// 遍历后 , 会返回一个新的 Map 集合
// 传入一个回调函数 , 参数是 key value , 返回值是新的 Map 集合
Map president2 = president.map(
(key, value){
// 这里将 Map 集合中的 Key 和 Value 进行颠倒 , 生成一个新的 Map 集合
return MapEntry(value, key);
}
);

// 打印新的 Map 集合
print(president2);