Dart 类型系统与集合:类、泛型、List/Map/Set、null 安全
第 3 章 · Dart 类型系统与集合:类、泛型、List/Map/Set、null 安全
run
$cd examples/ch03-types-collections && dart pub get && dart run已验证
- dart analyze(0 告警)、dart test(32 个用例全绿)
- 完整工程已打包:打包下载
本章目录 · 13 节
3.1 本章目标
- 用 Dart 的类体系表达数据与行为:构造函数家族、
==/hashCode契约、extendsvsimplementsvssealed; - 理解 Dart 泛型是运行期具化的,以及"协变写入"这个会在运行期炸的洞;
- 掌握
List/Map/Set的惯用法(尤其是保持插入顺序这个和 Go 相反的细节); - 彻底搞懂 null 安全:
?、!、??、??=、类型提升、late; - 知道什么时候该写"值类型",什么时候该用 record。
本章内容直接决定你能不能读懂 Flutter 源码:Widget、State<T>、InheritedWidget 全是这些特性的组合。
3.2 类与对象:构造函数家族
// examples/ch03-types-collections/lib/money.dart
class Money implements Comparable<Money> {
const Money(this.cents, {this.currency = 'CNY'}); // 主构造 + 命名参数
factory Money.fromYuan(num yuan, {String currency = 'CNY'}) => // 工厂构造
Money((yuan * 100).round(), currency: currency);
final int cents;
final String currency;
double get yuan => cents / 100;
bool get isNegative => cents < 0;
Money operator +(Money other) { /* ... */ }
Money operator -(Money other) { /* ... */ }
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents && other.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
@override
int compareTo(Money other) => cents.compareTo(other.cents);
@override
String toString() => '${yuan.toStringAsFixed(2)} $currency';
}
构造函数有四种形态,一次记全:
| 形态 | 写法 | 用途 | C/Go 类比 |
|---|---|---|---|
| 主构造 | Money(this.cents) |
最常用;this.x 自动赋值 |
struct 初始化器 |
| 命名构造 | Money.withCurrency(...) : this(...) |
多个初始化入口 | new_money_with_currency() |
| 工厂构造 | factory Money.fromYuan(...) |
可以返回缓存/子类,可以不做 new |
工厂函数 |
const 构造 |
const Money(100) |
编译期常量,用于 const 树 |
#define 常量 struct |
关键差异:
- 没有析构函数。C 里每个
malloc都要配free;Dart 只有 GC,没有~T()。资源(文件、Socket、StreamSubscription)要靠close()/dispose()显式释放——遗忘就泄漏(ch05、ch06 会具体讲)。 final字段必须在构造时赋值,且编译期保证不再变。这比 C 的const成员严格得多。- 没有
const方法的区分(C++ 的int f() const)。Dart 里"不可变"要么靠final字段,要么靠"不提供 setter"。
== / hashCode 契约(本章第一个大坑)
Dart 的 == 默认是引用相等,也就是 identical:
<int>[1, 2] == <int>[1, 2] // false!
const [1, 2] == const [1, 2] // true(const 被规范化成同一对象)
| 语言 | struct/类 的 == |
集合的 == |
|---|---|---|
| C | 需要 memcmp 或逐字段手写(危险) |
不存在 |
| Go | 自动逐字段(若字段都可比较) | slice/map 不可比较(只能和 nil 比) |
| Dart | 默认引用相等,要值语义必须手写 | List/Map 也是引用相等 |
要让 Money 能放进 Set、当 Map 的 key、被 expect 断言值相等,必须同时重写 == 和 hashCode,并且满足:
a == b时a.hashCode == b.hashCode;==必须自反、对称、传递;hashCode用到的字段必须和==用到的字段一致。
Object.hash(...) 帮你做字段混合(比手写 31 * h1 + h2 安全,Go 程序员会想到 hash/fnv)。
Flutter 里大量"为什么我的列表没刷新""为什么
Set里去重没生效",根因都是没重写==/hashCode。ch11 的 Riverpod 也依赖这一点。
3.3 继承、接口与 sealed
Dart 是单继承 + 任意多接口:
abstract class Shape {
const Shape();
double get area; // 抽象成员
String describe() => '$runtimeType(area: ...)'; // 具体方法
}
abstract interface class Describable {
String describe();
}
class NamedCircle extends Circle implements Describable, Comparable<NamedCircle> {
const NamedCircle(super.radius, this.name); // super.参数 把参数转发给父类
final String name;
@override
String describe() => '$name: ${super.describe()}';
@override
int compareTo(NamedCircle other) => name.compareTo(other.name);
}
| 项 | Go | Dart |
|---|---|---|
| 接口 | 隐式实现(方法集匹配) | 隐式接口(任何类都能被 implements)+ interface class 显式声明 |
| 继承 | 无,只有嵌入(composition) | 单继承 extends |
| 多态 | 接口值 + 方法集 | 虚表(vtable),行为和 C++ 相同 |
| 类型断言 | v, ok := x.(T) |
x is T、x as T |
sealed + 模式匹配:穷尽性检查
sealed class Shape2 {
const Shape2();
double get area;
}
final class Circle extends Shape2 { /* ... */ }
final class Rectangle extends Shape2 { /* ... */ }
final class Triangle extends Shape2 { /* ... */ }
String label(Shape2 shape) => switch (shape) {
NamedCircle(:final name, :final radius) => '命名圆 $name r=$radius',
Circle(:final radius) => '圆形 r=$radius',
Rectangle(:final width, :final height) => '矩形 ${width}x$height',
Triangle(:final base, :final height) => '三角形底 $base 高 $height',
};
sealed 的含义:子类必须在同一个库里,因此编译器知道全部子类型,switch 少写一个分支就是编译错误。
这相当于 Rust 的 match + enum、TypeScript 的 discriminated union。Go 没有(switch x.(type) 不检查穷尽性),C 更没有。在 Flutter 里,这对"状态机"(loading/error/data,ch13)极其有用:只要新增了一个状态,所有 switch 都会亮红灯。
编译期踩坑记录:本示例最初把
Circle写成final class,然后NamedCircle extends Circle,编译器直接报The type 'NamedCircle' must be 'base', 'final' or 'sealed' because the supertype 'Circle' is 'final'。final class是"禁止被继承"的标记,这一点和 C++ 的final、sealed关键字同义。想被继承就写class,想禁止就写final class。
3.4 泛型:具化(reified)的泛型
// examples/ch03-types-collections/lib/generics.dart
T maxOf<T extends Comparable<T>>(List<T> xs) { /* ... */ }
class Box<T> {
const Box(this.value);
final T value;
Box<R> map<R>(R Function(T value) transform) => Box<R>(transform(value));
}
bool isIntList(Object value) => value is List<int>; // 运行期能分辨!
| 项 | Go | Dart | C |
|---|---|---|---|
| 泛型 | 编译期实例化/形状化,运行期没有类型参数 | 运行期保留类型参数(具化) | 只有宏/void* |
| 约束 | type T interface{ ~int | ~string } |
T extends Comparable<T> |
无 |
| 运行期判断 | 不能 x.([]int) 之外的方式区分 |
value is List<int> 精确区分 |
无 |
| 零值 | var zero T |
没有零值概念(必须传 seed) | — |
sumOf 需要 seed 参数,就是"没有零值"的直接后果:
T sumOf<T extends num>(List<T> xs, {required T seed}) {
var total = seed;
for (final x in xs) total = (total + x) as T;
return total;
}
Go 里你写 var zero T; for _, x := range xs { zero += x },Dart 里做不到,因为 T 可能是 double,凭空造出的 0 是 int。
协变(covariance)陷阱
List<num> widenToNum(List<int> xs) => xs; // 允许:List<int> 是 List<num> 的子类型
void addDouble(List<num> xs) => xs.add(1.5);
addDouble(widenToNum(<int>[1, 2])); // 编译通过,运行期 TypeError
Dart(以及 Java、C# 数组)的泛型是协变的:List<int> 可以当 List<num> 用,但写操作靠运行期检查兜底。Go 的泛型是编译期严格检查,没有这个洞;C 根本没有泛型,所以也没有这种"安全假象"。
实践结论:不要把 List<int> 之类的具体容器当父类型参数传出去,宁可让函数签名更精确,或者直接传 Iterable<T>(只读)。
3.5 集合:List / Set / Map
// examples/ch03-types-collections/lib/collections.dart
List<int> squaresOfEven(List<int> xs) =>
xs.where((int x) => x.isEven).map((int x) => x * x).toList();
Map<int, List<String>> groupByLength(List<String> words) {
final result = <int, List<String>>{};
for (final w in words) {
(result[w.length] ??= <String>[]).add(w);
}
return result;
}
List<int> sortedDescending(List<int> xs) => [...xs]..sort((int a, int b) => b.compareTo(a));
| 项 | Go | Dart |
|---|---|---|
| 动态数组 | []int(slice,底层数组共享) |
List<int>(对象,永远引用) |
| 键值表 | map[K]V,遍历顺序随机 |
Map<K,V>,保持插入顺序 |
| 集合 | 无内置(用 map[T]struct{}) |
Set<T>(LinkedHashSet,保持插入顺序) |
| 原地排序 | sort.Ints(xs) |
xs.sort() 原地 + [...xs] 复制 |
| 只读 | 无(靠约定) | List.unmodifiable / List<int>.filled(n, x) |
| 判空 | len(xs) == 0 |
xs.isEmpty / xs.isNotEmpty |
| 追加 | append(xs, v)(可能换底层数组) |
xs.add(v)(永远是同一个对象) |
最容易踩的差异:Dart 的 Map 是有序的(LinkedHashMap),所以 {...}{'a','b','c'} 遍历永远按插入顺序;Go 的 map 遍历顺序每次都不一样,写测试时你从不敢断言顺序——在 Dart 里可以。
三个高频陷阱:
sort是原地修改。final sorted = xs.sort()返回值是void,不是新列表。要保留原列表必须[...xs]..sort()(级联运算符..是 Dart 特有语法,见 ch08)。List.filled(n, x)默认是定长。add会抛UnsupportedError,但list[0] = ...可以改。map/where是惰性的(返回Iterable),链式调用后必须.toList()才真正求值;把Iterable放在for里多次遍历会重复计算。
集合推导(collection-if / collection-for / spread)是 Dart 的独门语法,写 UI 列表时天天用:
List<String> buildTags({bool starred = false, List<String> extra = const [], List<String>? more}) => [
'dart',
if (starred) 'starred',
for (final e in extra) 'extra:$e',
...?more, // ...? 对可空集合展开,null 时跳过
];
3.6 null 安全:null 是类型问题,不是运行时惊喜
String displayName(String? name) { // 可空入参
if (name == null || name.trim().isEmpty) return 'anonymous';
return name.trim();
}
String shout(String? s) {
if (s == null) return '...';
return s.toUpperCase(); // 类型提升:s 已经是 String
}
String configOrDefault(Map<String, String> cfg, String key) => cfg[key] ?? 'default';
String cityOfUser(Map<String, Object?>? user) {
final address = user?['address']; // ?. 短路
if (address is! Map<String, Object?>) return '未知';
return (address['city'] as String?) ?? '未知';
}
| 表达"无值" | C | Go | Dart |
|---|---|---|---|
| 手段 | NULL 裸指针 |
nil(指针/接口/chan/map/slice 都是) |
T?(类型系统的一部分) |
| 检查时机 | 无(UB) | 运行时 panic | 编译期 |
| 解引用 | *p 崩溃 |
p.field panic |
s.length 编译不过;必须 ?. / 判空 / ! |
| 默认值 | p ? p : d |
if v == nil |
??、??= |
| 延迟初始化 | 手写懒汉 | sync.Once |
late final |
四种操作符,一次讲清:
| 操作符 | 含义 | 风险 |
|---|---|---|
T? |
可以是 null 的类型 |
每次使用都要处理 |
?. |
为 null 就短路成 null | 链式调用结果整体变可空 |
! |
"我保证不为 null" | 猜错 → TypeError: Null check operator used on a null value |
late |
"我先声明,稍后一定赋值" | 猜错 → LateInitializationError(运行期) |
late final 是唯一"延迟初始化 + 只读"的写法:
class LazyConfig {
int computeCount = 0;
late final String dbPath = _computePath(); // 第一次读取时才执行
String _computePath() { computeCount++; return '/tmp/ch03-app.db'; }
}
实测:读到 dbPath 之前 computeCount == 0;读一次后变成 1;再读仍是 1。这比 Go 的 sync.Once 简洁,但不是线程安全的——Dart 单线程(isolate 之间不共享内存),所以不需要锁,这是整个并发模型差异的伏笔(ch05、ch08)。
陷阱:
late把编译期检查挪到了运行期。能不用就不用;用String?让调用方处理更诚实。 另外:LateInitializationError是内部类型,dart:core里没有公开的类名可以isA<LateInitializationError>()——示例里最初写了这个断言,编译直接失败(isn't a type),最后改成断言错误信息包含LateInitializationError。
类型提升(type promotion)为什么好用
String f(String? s) {
if (s == null) return '...';
return s.toUpperCase(); // 编译器知道 s 在这里不是 null
}
只对局部变量和**final 字段**生效。this.field 这种实例字段不做提升(因为字段可能在 if 之后被改),需要在方法里先 final local = field; 再判空。这是 Dart 里非常常见的写法,例如 ch06 的 mounted 检查。
3.7 运行与验证
cd examples/ch03-types-collections
dart pub get && dart analyze && dart test && dart run
真实输出(节选):
coffee = 20.50 CNY, tea = 20.50 CNY
coffee == tea ? true identical? false
earth (2/3): g = 9.82 m/s²
圆形 r=1.0 → 3.14
总面积 = 34.14
偶数的平方: [4, 16, 36]
按长度分组: {2: [go], 4: [dart, rust], 1: [c], 7: [flutter]}
词频: {the: 3, quick: 1, lazy: 1, dog: 1}
协变写入被运行期拦下: _TypeError
dbPath = /tmp/ch03-app.db, 计算次数 = 1
late 未初始化: LateError
注意 earth (2/3):字符串插值里 $values.length 会解析成 ${values}.length(先插值再取 .length),得到 [Planet.mercury, ...].length 这种鬼东西。必须写 ${values.length}。这是 Dart 插值最常见的坑,和 C 的 printf 优先级问题异曲同工。
附:C/Go 代码对照:结构相等
// Go:结构体默认逐字段比较,可直接做 map key
type Money struct {
Cents int
Currency string
}
a := Money{100, "CNY"}
b := Money{100, "CNY"}
fmt.Println(a == b) // true
set := map[Money]struct{}{a: {}}
fmt.Println(len(set)) // 1
// 一旦字段里有 slice/map,结构体就不可比较,只能手写 Equal
// Dart:默认是引用相等,必须手写 == 和 hashCode(本章的 Money)
class Money {
const Money(this.cents, {this.currency = 'CNY'});
final int cents;
final String currency;
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents && other.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
}
Money(100) == Money(100); // true(重写之后)
<int>[100] == <int>[100]; // false(集合没有结构相等)
陷阱:只重写 == 不重写 hashCode,Set 去重和 Map 查找都会失效——Go 里不存在这个问题。
3.8 本章小结 + C/Go 对照清单
| 主题 | C | Go | Dart | 陷阱 |
|---|---|---|---|---|
| 结构相等 | 手写 memcmp |
struct 自动 | 手写 == + hashCode |
忘了 hashCode → Set/Map 失效 |
| 构造 | struct 初始化器 |
结构体字面量 | 主/命名/工厂/const 四种 |
const 构造要求所有字段 final |
| 继承 | 无 | 嵌入 | 单继承 + 多接口 | final class 不能继承 |
| 穷尽匹配 | 只能 switch + 手写 default: abort() |
switch x.(type) 不查穷尽 |
sealed + switch 表达式编译期穷尽 |
— |
| 泛型 | 宏/void* |
编译期实例化 | 运行期具化、协变 | 往 List<num> 塞 double 运行期炸 |
| 零值 | 0/memset |
var zero T |
没有 | 泛型求和要传 seed |
| Map 顺序 | 无内置 | 随机 | 插入顺序 | 迁移 Go 代码时容易误以为无序 |
| 排序 | qsort |
sort.Ints(原地) |
sort()(原地) |
忘了复制就改脏原数据 |
| null | NULL + UB |
nil + panic |
T? + 编译期检查 |
! 和 late 都是"删掉检查"的逃生门 |
给 C/Go 老兵的三句话:
- Dart 的
==默认是identical;值语义要自己写,且必须配hashCode。 - 泛型是运行期具化的,
is List<int>真的能分辨——代价是协变写入的洞。 - null 安全是类型系统的一部分:
!、late是在关掉这套系统,用之前先问自己"有没有更诚实的方式"。
下一章回到 Flutter:Row/Column/Stack 和约束(constraint)系统。你会发现,Flutter 的布局就是"把约束往下传、把尺寸往上传",和本项目的类型系统一样,都是规则先行的声明式思维。