127 字
1 分钟
Dart isolate compute() 报错
调用 compute
方法,报错:Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)
现象
Future<List<DataModel>> fetchData() async{
final response = await http.get("https://api.themoviedb.org/3/movie/now_playing?api_key=d81172160acd9daaf6e477f2b306e423&language=en-US");
if(response.statusCode == 200){
return compute(createDataList,response.body.toString());
}
}
List<DataModel> createDataList(String responFroJson) {
final parse = json.decode(responFroJson).cast<Map<String, dynamic>>();
return parse.map<DataModel> ((json) => DataModel.fromtJson(json)).toList();
}
解决
将调用 compute
的方法移至任何Class的外部,例:
// [createDataList]放在[SomeClass]的外面
List<DataModel> createDataList(String responFroJson) {
...
}
class SomeClass { ... }
原因
在isolate之间传递的object会发生复制,外部资源有关联的对象不能在isolate之间传。
链接
Dart isolate compute() 报错
https://blog.lpkt.cn/posts/dart-compute-isolate/