本文最后更新于261 天前,其中的信息可能已经过时,如有错误请发送邮件到zhizihua030611@163.com
变量
可以用 var 来定义变量,不用显式指定他们的类型,支持类型推断。
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg',
};
关键字
基本结构关键字
| 关键字 | 用途说明 | 示例 |
|---|---|---|
import | 导入库 | import 'dart:math'; |
library | 声明库名 | library my_library; |
export | 导出库成员 | export 'src/utils.dart'; |
part | 声明部分库文件 | part 'part1.dart'; |
part of | 声明属于某个库 | part of main_library; |
typedef | 创建类型别名 | typedef IntList = List<int>; |
变量与类型
| 关键字 | 用途说明 | 示例 |
|---|---|---|
var | 类型推断变量 | var name = 'Dart'; |
final | 运行时常量 | final pi = 3.14; |
const | 编译时常量 | const maxSize = 100; |
dynamic | 动态类型 | dynamic value = 5; |
void | 无返回值类型 | void main() {...} |
late | 延迟初始化 | late String description; |
required | 必需命名参数 | Person({required this.name}); |
流程控制
| 关键字 | 用途说明 | 示例 |
|---|---|---|
if/else | 条件判断 | if (isRaining) {...} else {...} |
for | 循环 | for (var i=0; i<5; i++) |
while | 当循环 | while (!isDone) {...} |
do | do-while 循环 | do {...} while (condition); |
switch/case | 多分支选择 | switch (command) { case 'A': ... } |
break | 跳出循环 | break; |
continue | 跳过本次循环 | continue; |
return | 函数返回值 | return result; |
assert | 调试断言 | assert(text != null); |
异常处理
| 关键字 | 用途说明 | 示例 |
|---|---|---|
try | 异常捕获 | try {...} |
catch | 捕获异常 | catch (e) {...} |
on | 特定类型异常 | on FormatException {...} |
finally | 最终执行块 | finally {...} |
throw | 抛出异常 | throw FormatException(); |
rethrow | 重新抛出异常 | rethrow; |
面向对象编程
| 关键字 | 用途说明 | 示例 |
|---|---|---|
class | 定义类 | class Point {...} |
extends | 类继承 | class Orbiter extends Spacecraft {...} |
implements | 接口实现 | class MockSpaceship implements Spacecraft {...} |
with | 混入(mixin) | class Musician extends Person with Musical {...} |
mixin | 定义混入 | mixin Musical {...} |
abstract | 抽象类/方法 | abstract class Animal {...} |
factory | 工厂构造函数 | factory Logger() {...} |
super | 访问父类 | super.describe(); |
this | 当前实例 | this.name = name; |
new | 创建对象(可选) | var p = Point(); |
covariant | 协变参数类型 | void update(covariant View v) {...} |
函数相关
| 关键字 | 用途说明 | 示例 |
|---|---|---|
Function | 函数类型 | Function callback; |
async | 异步函数 | Future<void> main() async {...} |
await | 等待异步结果 | var data = await fetch(); |
sync | 同步生成器 | Iterable<int> count() sync* {...} |
yield | 生成值 | yield i; |
yield* | 委派生成器 | yield* countDown(); |
get | Getter 方法 | int get area => width * height; |
set | Setter 方法 | set radius(double r) {...} |
operator | 操作符重载 | Vector operator +(Vector v) {...} |
external | 外部函数声明 | external void log(String msg); |
高级类型系统
| 关键字 | 用途说明 | 示例 |
|---|---|---|
enum | 枚举类型 | enum Color { red, green, blue } |
extension | 扩展方法 | extension NumberParsing on String {...} |
sealed | 密封类(Dart 3.0+) | sealed class Shape {...} |
base | 基类修饰(Dart 3.0+) | base class Vehicle {...} |
interface | 接口类修饰(Dart 3.0+) | interface class DataStore {...} |
mixin class | 混入类(Dart 3.0+) | mixin class Animal {...} |
布尔与空值
| 关键字 | 用途说明 | 示例 |
|---|---|---|
true | 布尔真值 | var isActive = true; |
false | 布尔假值 | if (isValid == false) {...} |
null | 空值 | String? name = null; |
访问控制
| 关键字 | 用途说明 | 示例 |
|---|---|---|
show | 导入部分成员 | import 'lib.dart' show Foo; |
hide | 隐藏部分成员 | import 'lib.dart' hide Bar; |
deferred as | 延迟加载库 | import 'heavy.dart' deferred as heavy; |
其他特殊关键字
| 关键字 | 用途说明 | 示例 |
|---|---|---|
is | 类型检查 | if (obj is String) {...} |
as | 类型转换 | (obj as String).toUpperCase() |
in | 集合包含 | for (var item in list) {...} |
await for | 异步循环 | await for (var event in stream) {...} |
@override | 方法重写注解 | @override void paint() {...} |
@protected | 保护成员注解 | @protected void internalMethod() |
流程控制语句
if (year >= 2001) {
print('21st century');
} else if (year >= 1901) {
print('20th century');
}
for (final object in flybyObjects) {
print(object);
}
for (int month = 1; month <= 12; month++) {
print(month);
}
while (year < 2016) {
year += 1;
}
同时还包括 break 和 continue 关键字、 switch 语句和 case 子句 以及 assert 语句。
函数
tips:为每个函数的参数以及返回值都指定类型:
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
匿名函数:
用 => 简写语法用于仅包含一条语句的函数。
flybyObjects.where((name) => name.contains('turn')).forEach(print);
导入(import)
// Importing core libraries
import 'dart:math';
// Importing libraries from external packages
import 'package:test/test.dart';
// Importing files
import 'path/to/my_other_file.dart';
类(class)
下面的示例中向你展示了一个包含三个属性、两个构造函数以及一个方法的类。其中一个属性不能直接赋值,因此它被定义为一个 getter 方法(而不是变量)。该方法使用字符串插值来打印字符串文字内变量的字符串。
class Spacecraft {
String name; // 航天器名称
DateTime? launchDate; // 发射日期(可为空)
// 只读的非final属性(计算属性)
// 当launchYear 为非空时返回年份,否则返回null
int? get launchYear => launchDate?.year;
// 构造函数,使用语法糖将参数直接赋值给成员变量
Spacecraft(this.name, this.launchDate) {
// 初始化代码写在这里
}
// 命名构造函数,转发到默认构造函数
Spacecraft.unlaunched(String name) : this(name, null);
// 方法:描述航天器信息
void describe() {
print('航天器名称: $name');
// 类型提升对getter无效,需要先复制到局部变量
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365;
print('发射时间: $launchYear ($years 年前)');
} else {
print('未发射');
}
}
}
使用示例
void main() {
// 已发射航天器
final apollo = Spacecraft("阿波罗11号", DateTime(1969, 7, 16));
apollo.describe();
// 未发射航天器
final probe = Spacecraft.unlaunched("火星探测器");
probe.describe();
}
输出
航天器名称: 阿波罗11号
发射时间: 1969 (55 年前)
航天器名称: 火星探测器
未发射
枚举类型(Enum)
枚举类型的取值范围是一组预定义的值或实例。
简单定义了一组行星类别
enum PlanetType { terrestrial, gas, ice }
增强枚举类型
enum Planet {
mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
// ··· (其他行星的类似定义)
uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);
/// 常量生成构造函数
/// 常量构造:使用const构造函数确保编译时常量
const Planet({
required this.planetType,
required this.moons,
required this.hasRings,
});
/// 所有实例变量都是final(不可变的)
final PlanetType planetType;
final int moons;
final bool hasRings;
/// 增强型枚举支持getter和其他方法
/// 当行星类型是气态巨行星或者冰态巨行星时返回true
bool get isGiant =>
planetType == PlanetType.gas || planetType == PlanetType.ice;
}
使用示例
print(Planet.jupiter.isGiant); // 输出: true
print(Planet.earth.isGiant); // 输出: false
扩展类(继承)
Dart只支持单继承
class Orbiter extends Spacecraft {
double altitude;
Orbiter(super.name, DateTime super.launchDate, this.altitude);
}
当需要重写父类方法时,用到@override注解
class Orbiter extends Spacecraft {
double altitude;
Orbiter(super.name, DateTime super.launchDate, this.altitude);
// 使用 @override 重写父类方法
@override
void describe() {
super.describe(); // 可选:调用父类实现
print('轨道高度: $altitude 公里');
}
// 重写 getter
@override
int? get launchYear {
// 自定义逻辑
return super.launchYear;
}
}
接口和抽象类
所有的类都隐式定义成一个接口。因此,任意类都可以作为接口被实现。
class MockSpaceship implements Spacecraft {
// ···
}
你可以创建一个被任意具体类扩展(或实现)的抽象类。抽象类可以包含抽象方法(不含方法体的方法)。
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
任意一个扩展了 Describable 的类都拥有 describeWithEmphasis() 方法,这个方法又会去调用实现类中实现的 describe() 方法。
异步
使用 async 和 await 关键字可以让你避免回调地狱 (Callback Hell) 并使你的代码更具可读性
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}


