Dart 空安全与异步基础
Dart 2.12 引入空安全(null safety),Dart 3 完全强制。配合 async/await/Future/Stream,异步编程是 Flutter 日常 80% 的代码形态。
一、空安全:String vs String?
String name = '张三'; // 不能为 null
String? maybe; // 可以为 null,默认 null
print(name.length); // ✅
print(maybe.length); // ❌ 编译错
print(maybe?.length); // ✅,maybe 是 null 时返回 null
print(maybe!.length); // ✅ 强制非 null,运行时若为 null 抛错常用空操作符
| 操作符 | 含义 |
|---|---|
? | 类型可空,或方法链短路 |
! | 强制断言非 null,用错就崩 |
?? | 默认值:a ?? b 等价于 a == null ? b : a |
??= | 仅当为 null 时赋值:a ??= b |
?. | 安全方法链 |
?.. | 安全级联(级联调用) |
final name = maybe ?? '匿名';
final list = items ?? [];
cache ??= computeExpensive(); // 没缓存才算late:延迟初始化的非空
class _MyState extends State<MyWidget> {
late final AnimationController _ctrl;
@override
void initState() {
super.initState();
_ctrl = AnimationController(vsync: this, duration: Duration(seconds: 1));
// 现在初始化,_ctrl 类型是非空
}
}late 告诉编译器"我保证用之前赋值",换来非空类型。 ⚠️ 没赋值就用 → 运行时 LateInitializationError。
late 修饰函数(惰性求值)
late final config = loadHeavyConfig(); // 第一次访问才执行第一次读取才算 loadHeavyConfig(),后续直接返回缓存。
required:命名参数必填
void greet({required String name, int age = 18}) { ... }
greet(name: '张三');回顾 28:Flutter 几乎全是 required。
二、空安全的实战陷阱
1. ! 是危险标志
final user = users.firstWhere((u) => u.id == id); // 找不到抛异常
final maybe = users.firstWhereOrNull((u) => u.id == id);
maybe!.name // ❌ 风险→ 用 if (maybe != null) 或 ??:
if (maybe != null) print(maybe.name);
final name = maybe?.name ?? '未知';2. List<String?> vs List<String>?
List<String?> a; // List 不为空,但元素可为空
List<String>? b; // List 可为空,但元素不为空
List<String?>? c; // 都可为空Map 同理:Map<String, int?> vs Map<String, int>?。读类型签名时分清楚两层 ?。
3. JSON 反序列化
final json = {'name': '张三', 'age': null};
final name = json['name'] as String; // ❌ 万一是 null 崩
final name = json['name'] as String?; // ✅ 容忍后端返回字段是否可能为 null,永远先按可空处理,见 34 freezed 章节。
4. setState 后用值
String? name;
fetch().then((v) {
name = v;
print(name.length); // ❌ 异步内 promotion 失效
});→ 局部变量 promotion 在异步边界丢失。先复制到 local:
final n = v;
print(n.length);5. 集合空值过滤
List<String?> raw = ['a', null, 'b'];
final cleaned = raw.whereType<String>().toList(); // ['a', 'b']whereType<T>() 只保留确实是 T 类型的元素,自动去掉 null。
三、Future:异步的"承诺"
Future<int> fetchAge() async {
await Future.delayed(const Duration(seconds: 1));
return 18;
}
void main() async {
final age = await fetchAge();
print(age);
}Future 状态
未完成 → (成功)→ value
→ (失败)→ error不用 await:链式
fetchAge().then((age) {
print(age);
}).catchError((e) {
print('错了 $e');
}).whenComplete(() {
print('结束');
});新代码 99% 用 async/await,只有"火忘"(fire and forget)场景用 then。
四、async / await
async 标记函数是异步的,返回 Future<T>。 await 等 Future 完成,值会被解包。
Future<String> getUserName() async {
final user = await fetchUser(); // 等
return user.name;
}错误处理
Future<void> save() async {
try {
await api.save(data);
} on DioException catch (e) {
print('网络错 ${e.message}');
} catch (e, st) {
print('其他 $e\n$st');
} finally {
setState(() => _saving = false);
}
}并发执行
// ❌ 串行,慢
final a = await fetchA();
final b = await fetchB();
// ✅ 并行,快
final results = await Future.wait([fetchA(), fetchB()]);
final a = results[0];
final b = results[1];
// 类型安全的版本
final (a, b) = await (fetchA(), fetchB()).wait; // Dart 3 recordFuture.wait 的注意
await Future.wait([
fetchA(),
fetchB(),
fetchC(),
]);
// 任一失败,整个抛错(默认)
// 想要"全部完成不管对错":
await Future.wait([f1, f2, f3], eagerError: false);Future.any
final winner = await Future.any([
fetchPrimary(),
fetchBackup(),
]);哪个先完成用哪个,适合"主从备援"。
五、Future 的常用方法
Future.value(42); // 立即完成
Future.error('boom'); // 立即失败
Future.delayed(const Duration(seconds: 1)); // 延迟
Future.delayed(Duration(seconds: 1), () => 42);
future.timeout(Duration(seconds: 5)); // 超时
future.timeout(Duration(seconds: 5), onTimeout: () => '默认值');六、Completer:手动控制 Future
class MyWidget extends StatefulWidget {
@override State<MyWidget> createState() => _S();
}
class _S extends State<MyWidget> {
final _completer = Completer<GoogleMapController>();
@override
Widget build(_) => GoogleMap(
onMapCreated: (ctrl) => _completer.complete(ctrl),
);
Future<void> _moveCamera() async {
final ctrl = await _completer.future; // 等地图初始化完
ctrl.animateCamera(...);
}
}适合"事件转 Future"的场景。
七、Stream:多次推送的"未来"
Future = 一次性结果,Stream = 持续多次的结果序列。
Stream<int> counter() async* {
for (var i = 0; i < 5; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
void main() async {
await for (final i in counter()) print(i); // 0 1 2 3 4
}async* 标记 generator,yield 推一个值。
监听
final sub = counter().listen(
(i) => print(i),
onError: (e) => print('错 $e'),
onDone: () => print('完'),
);
// 取消
sub.cancel();⚠️ 没 cancel → 内存泄漏。Widget dispose 必须 cancel(回顾 06)。
Stream 操作
stream.where((x) => x > 0)
.map((x) => x * 2)
.take(3) // 只取前 3 个
.skip(1) // 跳过第 1 个
.distinct() // 去重
.debounceTime(...) // 节流(rxdart)
.toList(); // 收集成 List八、StreamController:手动制造 Stream
final ctrl = StreamController<int>();
ctrl.stream.listen((i) => print(i));
ctrl.add(1);
ctrl.add(2);
ctrl.addError('boom');
ctrl.close();单订阅 vs 广播
StreamController<int>(); // 单订阅:同一时刻只能 listen 一次
StreamController<int>.broadcast(); // 广播:多个 listener 共享UI 多处订阅同一数据用 .broadcast。
rxdart 的 BehaviorSubject
import 'package:rxdart/rxdart.dart';
final subject = BehaviorSubject<int>.seeded(0); // 缓存最新值
subject.add(1);
subject.add(2);
// 后来的订阅者立刻收到 2(缓存了)
subject.listen((i) => print(i));类似 ReactiveX,但 Flutter 自带的 Stream 已经够用,不必无脑上 rxdart。
九、Stream 在 UI 里:StreamBuilder
StreamBuilder<int>(
stream: counter(),
initialData: 0,
builder: (_, snap) {
if (snap.hasError) return Text('错:${snap.error}');
return Text('${snap.data}');
},
)类似的 FutureBuilder:
FutureBuilder<User>(
future: fetchUser(),
builder: (_, snap) {
if (snap.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snap.hasError) return Text('错:${snap.error}');
return Text(snap.data!.name);
},
)注意:FutureBuilder 在父级 rebuild 时如果 future 是新对象,会重新跑。build 方法里不要直接 future: fetch():
// ❌ 每次 rebuild 都重新请求
FutureBuilder(future: fetch(), ...)
// ✅ 把 future 缓存到 State
late final _future = fetch();
@override
Widget build(_) => FutureBuilder(future: _future, ...)或用 Riverpod / Bloc 管理(推荐,见 09 / 10)。
十、Zone:全局错误捕获
异步代码抛错没人 catch 会变成"未处理异常",App 可能崩。Zone 可以包一个范围,所有未处理错误进它的 handler。
runZonedGuarded(() {
runApp(MyApp());
}, (error, stack) {
// 任何异步未捕获错误都到这里
Sentry.captureException(error, stackTrace: stack);
});回顾 19 / 36:崩溃监控的根基。
十一、isolate(简介)
Dart 单线程,大计算 isolate 里跑(详细 37):
final result = await Isolate.run(() => heavyCalc(input));
final json = await compute(jsonDecode, text);十二、常见坑
1. await 忘了
Future<void> save() async {
api.save(data); // ❌ 没 await,函数里这一行立刻返回
}→ Lint 会警告,但要养成肌肉记忆。
2. async 函数返回非 Future
// ❌ async 自动包成 Future,但 return 不是 Future 类型不匹配
Future<int> get() async => Future.value(1); // 返回 Future<Future<int>>?
// ✅
Future<int> get() async => 1; // 自动包成 Future<int>async 函数 return 的值会自动包 Future,不要再手动包。
3. 在 List.forEach 里 await
[1,2,3].forEach((i) async {
await Future.delayed(...);
print(i);
});
print('done'); // ❌ 立刻打印,forEach 不等→ 用 for await 或 Future.wait:
for (final i in [1,2,3]) {
await delay();
print(i);
}4. Stream 多次 listen 报错
final s = counter();
s.listen(print);
s.listen(print); // ❌ 单订阅 stream→ 改 broadcast,或在源头用 .asBroadcastStream()。
5. await 在循环里串行
for (final id in ids) {
await fetch(id); // 一个一个等
}
// 想并行:
await Future.wait(ids.map(fetch));6. 异步过的 BuildContext
回顾 04:await 后用 context 必须 mounted 守卫。
十三、和已学知识的串联
- Future / Stream + Riverpod =
FutureProvider/StreamProvider(09) - Bloc 的状态变化本质就是 Stream(10)
- 网络请求 Dio 返回 Future(13)
- 数据库流式查询返回 Stream(14)
- mounted 守卫(04 / 06)
- 错误进 Zone 上报 Sentry(36)
十四、心智模型
空安全:
String = 必有
String? = 可空
late T = 我保证用前赋值
T? 用 ?. / ?? / ! 处理空
异步:
Future = 一次性结果
Stream = 多次推送
async/await 写起来像同步
并行用 Future.wait
全局兜底用 runZonedGuarded空安全和异步是 Dart 最值得花时间的两个特性。掌握了,你能彻底不再写出 NullPointerException 和 race condition——前端 / Java / Python 老坑能减少 80%。