使用Dart Isolate处理JSON解析时出现不可发送对象错误求助
问题:Flutter中使用Isolate解析JSON时出现“不可发送对象”错误
我在Flutter包中尝试用Dart Isolate卸载JSON解析任务,但运行函数时遇到Isolate消息存在“不可发送对象”的错误。
代码示例
Future<Map<String, dynamic>?> _extractResponse(String url) async { try { final response = await fetchWithRetry(url, maxAttempts: maxAttempts ?? 3); if (response.statusCode == 200) { print('fetching result'); final jsonMap = await Isolate.run(() { return _requestAndContent(response.body); }); // 后续逻辑... } // 其他逻辑... } catch (e) { // 错误处理 } }
错误信息
Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _Future@4048458 (see restrictions listed at `SendPort.send()` documentation for more information) <- _streamFuture in Instance of '_HttpClientConnection' (from dart:_http) <- hashCode in Instance of '_HashSetEntry<_HttpClientConnection>' (from dart:collection) <- _List len:8 (from dart:core) <- _buckets in Instance of '_HashSet<_HttpClientConnection>' (from dart:collection) <- _idle in Instance of '_ConnectionTarget' (from dart:_http) <- value in Instance of '_HashMapEntry' (from dart:collection) <- _List len:8 (from dart:core)...
已尝试的解决方法
- 将
_requestAndContent改为同步而非异步 - 使用
response.body.toString()
解决方案
问题根源
错误核心原因:Isolate.run的闭包会隐式捕获外部的response对象,而HTTP响应对象内部包含不可序列化的资源(比如HTTP连接实例、Future对象),这些对象无法跨Isolate传递——哪怕你只在闭包里使用response.body,整个response对象仍会被尝试发送到Isolate,从而触发错误。
修复代码
提前提取response.body为独立字符串变量,让Isolate闭包只依赖这个纯可序列化的字符串,避免捕获整个response对象:
Future<Map<String, dynamic>?> _extractResponse(String url) async { try { final response = await fetchWithRetry(url, maxAttempts: maxAttempts ?? 3); if (response.statusCode == 200) { print('fetching result'); // 提前提取body字符串,隔离不可序列化的response对象 final responseBody = response.body; final jsonMap = await Isolate.run(() { return _requestAndContent(responseBody); }); // 后续逻辑... } // 其他逻辑... } catch (e) { // 错误处理 rethrow; } }
关键说明
Dart Isolate之间传递的消息必须是可序列化的基础类型(字符串、数字、列表、Map等),任何包含内部状态、资源引用的对象(比如HTTP连接、文件句柄、Future)都无法跨Isolate传递。因此必须确保传递给Isolate的只有纯数据,不包含任何带资源的对象。
内容的提问来源于stack exchange,提问作者Jonathan Getachew
相关产品推荐
相关产品推荐

