一、基础 Isolate 使用
场景:计算密集型任务
import 'dart:isolate';
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(
fibonacciIsolate,
{'sendPort': receivePort.sendPort, 'n': 40},
);
receivePort.listen((message) {
print('斐波那契结果: $message');
receivePort.close();
});
}
void fibonacciIsolate(Map<String, dynamic> data) {
final sendPort = data['sendPort'] as SendPort;
final n = data['n'] as int;
sendPort.send(fibonacci(n));
}
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
二、长时间后台任务
场景:定时上报进度
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(backgroundTask, receivePort.sendPort);
receivePort.listen((progress) {
print('当前进度: $progress%');
if (progress >= 100) receivePort.close();
});
}
void backgroundTask(SendPort sendPort) {
for (int i = 0; i <= 100; i += 10) {
sendPort.send(i);
Isolate.sleep(Duration(seconds: 1));
}
}
三、多 Isolate 协作
场景:并行处理多个任务
void main() async {
final results = await Future.wait([
compute(fibonacci, 40),
compute(factorial, 20),
]);
print('结果: $results');
}
int factorial(int n) => n == 0 ? 1 : n * factorial(n - 1);
四、双向通信
场景:主 Isolate 与子 Isolate 对话
void main() async {
final mainReceivePort = ReceivePort();
final isolate = await Isolate.spawn(
echoIsolate,
mainReceivePort.sendPort,
);
mainReceivePort.listen((message) {
print('收到: $message');
if (message == 'Hello') {
(message as SendPort).send('你好,子 Isolate!');
}
});
mainReceivePort.sendPort.send('Hello');
}
void echoIsolate(SendPort mainSendPort) {
final isolateReceivePort = ReceivePort();
mainSendPort.send(isolateReceivePort.sendPort);
isolateReceivePort.listen((message) {
print('子收到: $message');
mainSendPort.send('收到: $message');
});
}
五、使用 compute
简化操作
场景:快速并行计算
import 'dart:async';
import 'package:flutter/foundation.dart';
void main() async {
final result = await compute(fibonacci, 40);
print('计算结果: $result');
}
关键概念总结
- 内存隔离:Isolate 间不共享内存,通过
SendPort
传递可序列化数据。
- 错误处理:在 Isolate 内使用
try-catch
捕获异常,通过端口发送错误信息。
- 性能考量:适合 CPU 密集型任务,避免用于高频小消息通信。
- Flutter 集成:使用
compute
在 Flutter 中简化后台任务,防止 UI 卡顿。
错误处理示例
void main() async {
final receivePort = ReceivePort();
await Isolate.spawn(
errorTask,
receivePort.sendPort,
onError: receivePort.sendPort,
onExit: receivePort.sendPort,
);
receivePort.listen((message) {
if (message is List && message[0] is String) {
print('错误: ${message[1]}');
} else {
print('结果: $message');
}
receivePort.close();
});
}
void errorTask(SendPort sendPort) {
try {
final result = someDangerousOperation();
sendPort.send(result);
} catch (e) {
sendPort.send(['error', e.toString()]);
}
}