我试图使用moviedb API从Internet上获取数据,我遵循了https://flutter.io/cookbook/networking/fetch-data/上的教程
但出现以下错误。
无效的参数:隔离消息中的非法参数:(对象是闭包-函数'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();
}
答案 0 :(得分:12)
class C
只能采用顶级方法或静态方法,而不能采用实例方法
f()
应该修复它,或者将其移到班级之外。
https://docs.flutter.io/flutter/foundation/compute.html
回调参数必须是顶级函数,而不是类的闭包,实例或静态方法。
答案 1 :(得分:2)
根据今天(2020年8月)的计算,使用静态方法可以正常工作。
对我来说,问题是我试图从compute()方法返回一个http.Response
对象。
我所做的是创建了该类的简化版本,其中包含我需要的内容:
class SimpleHttpResponse {
String body;
int statusCode;
Map<String, String> headers;
}
然后我从此更新了原始方法:
static Future<http.Response> _executePostRequest(EsBridge bridge) async {
return await http.post(Settings.bridgeUrl, body: bridge.toEncryptedMessage());
}
对此:
static Future<SimpleHttpResponse> _executePostRequest(EsBridge bridge) async {
http.Response result = await http.post(Settings.bridgeUrl, body: bridge.toEncryptedMessage());
if (result == null) {
return null;
}
SimpleHttpResponse shr = new SimpleHttpResponse();
shr.body = result.body;
shr.headers = result.headers;
shr.statusCode = result.statusCode;
return shr;
}
此更改后像魅力一样工作。希望这可以帮助遇到类似问题的人。
答案 2 :(得分:0)
简单的示例:
// this should be at class level
Future<int> heavyWork(int x) async {
// some heavy work which takes lot of time and you want it to be on a separate isolate
await Future.delayed(Duration(seconds: 5));
return x * x;
}
然后您将在窗口小部件中调用上述方法,
int result = await compute(heavyWork, 10); // prints 100 after 5 seconds