Dart | 语法

【Dart语法】


一、Hello, World!

1
2
3
4
void main() {
print('Hello, World!');
}

二、函数的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// A function declaration.
int timesTwo(int x) {
return x * 2;
}

// Arrow syntax is shorthand for `{ return expr; }`.
int timesFour(int x) => timesTwo(timesTwo(x));

// Functions are objects.
int runTwice(int x, int Function(int) f) {
for (var i = 0; i < 2; i++) {
x = f(x);
}
return x;
}

void main() {
print('4 times two is ${timesTwo(4)}');
print('4 times four is ${timesFour(4)}');
print('2 x 2 x 2 is ${runTwice(2, timesTwo)}');
}

三、List使用、函数控制

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
bool isEven(int x) {
// An if-else statement.
if (x % 2 == 0) {
return true;
} else {
return false;
}
}

List<int> getEvenNumbers(Iterable<int> numbers) {
var evenNumbers = <int>[];

// A for-in loop.
for (var i in numbers) {
// A single line if statement.
if (isEven(i)) {
evenNumbers.add(i);
}
}

return evenNumbers;
}

void main() {
var numbers = List.generate(10, (i) => i);
print(getEvenNumbers(numbers));
}

四、库的导入 、 Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'dart:math' as math;

void main() {
print('a single quoted string');
print("a double quoted string");

// Strings can be combined by placing them adjacent to each other.
print('cat' 'dog');

// Triple quotes define a multi-line string.
print('''triple quoted strings
are for multiple lines''');

// Dart supports string interpolation.
final pi = math.pi;
print('pi is $pi');
print('tau is ${2 * pi}');
}

五、数组、枚举、结构体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// A list literal.
const lostNumbers = [4, 8, 15, 16, 23, 42];

// A map literal.
const nobleGases = {
'He': 'Helium',
'Ne': 'Neon',
'Ar': 'Argon',
};

// A set literal.
const frogs = {
'Tree',
'Poison dart',
'Glass',
};

void main() {
print(lostNumbers.last);
print(nobleGases['Ne']);
print(frogs.difference({'Poison dart'}));
}

六、Class

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
// Abstract classes can't be instantiated.
abstract class Item {
void use();
}

// Classes can implement other classes.
class Chest<T> implements Item {
final List<T> contents;

// Constructors can assign arguments to instance variables using `this`.
Chest(this.contents);

@override
void use() => print('$this has ${contents.length} items.');
}

class Sword implements Item {
int get damage => 5;

@override
void use() => print('$this dealt $damage damage.');
}

// Classes can extend other classes.
class DiamondSword extends Sword {
@override
final int damage = 50;
}

void main() {
// The 'new' keyword is optional.
var chest = Chest<Item>([
DiamondSword(),
Sword(),
]);

chest.use();

for (final item in chest.contents) {
item.use();
}
}