Search code examples
functionparametersdartnotation

Dart: function's parameter notation


I sometimes find stuff like this:

Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('https://jsonplaceholder.typicode.com/photos');
return compute(parsePhotos, response.body);
}

where the parsePhotos function is:

List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

I can't understand the compute(parsePhotos, response.body): the parePhotos function takes in the responseBody parameter, but, as the compute is written, it seems that doesn't receive it. So, can someone explain me this notation, please? P.s. Hope it's clear enough.


Solution

  • In

    return compute(parsePhotos, response.body);
    

    parsePhotos and response.body are just two independent parameters. The first is a reference to the parsePhotos function passed to the computes callback parameter, and the second is is the response data from client.get(...) that is passed to the message parameter of the compute function.

    What compute does is to create a new isolate with parsePhotos as entry point (like main() for the main isolate) and then passes message to it as parameter.

    So it is not this line return compute(parsePhotos, response.body); that passes response.body to parsePhotos but

    final Isolate isolate = await Isolate.spawn(
        _spawn,
        new _IsolateConfiguration<Q, R>(
          callback,
          message,
    

    from the compute implementation https://docs.flutter.io/flutter/foundation/compute.html