Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)

I tried to fetch data from the internet with moviedb API, I followed the tutorial at https://flutter.io/cookbook/networking/fetch-data/

but I'm getting the below error.

Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)

This my code

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();
  }

Screenshot of the error message enter image description here

Upvotes: 54

Views: 30537

Answers (2)

Botond Kopacz
Botond Kopacz

Reputation: 942

As per today (2020. Aug) the compute is working fine with static methods. For me, the issue was that I was trying to return a http.Response object from the compute() methods.

What I did is I've created a simplified version of this class, containing what I need:

class SimpleHttpResponse {
  String body;
  int statusCode;
  Map<String, String> headers;
}

Then I've updated the original method from this:

static Future<http.Response> _executePostRequest(EsBridge bridge) async {
    return await http.post(Settings.bridgeUrl, body: bridge.toEncryptedMessage());
}
 

to this:

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;
}

Worked like charm after this change. Hope this helps somebody ranning into similar problem.

Upvotes: 7

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

compute can only take a top-level function, but not instance or static methods.

Top-level functions are functions declared not inside a class and not inside another function

List<DataModel> createDataList(String responFroJson) {
...
}

class SomeClass { ... }

should fix it.

https://docs.flutter.io/flutter/foundation/compute.html

R is the type of the value returned. The callback argument must be a top-level function, not a closure or an instance or static method of a class.

Upvotes: 102

Related Questions