Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing constructor as argument in Flutter

I have API communication service in my Flutter app with 10+ different services, and 100+ API calls that heed to parse data. In order to reuse code I've decided to create some common parsing code that is going to parse data from API:

ApiResponse handleObjectResponse({
    @required http.Response serverResponse,
    @required Function objectConstructor,
}) {
    if (serverResponse.statusCode == 200) {
      dynamic responseObject = objectConstructor(json.decode(serverResponse.body));
      return ApiResponse(responseObject: responseObject);
    } else {
      ApiError error = responseHasError(serverResponse.body);
      return ApiResponse(error: error);
    }
}

This way I am able to parse JSON object from API in a reusable way no matter what the Object class is, just by passing constructor function to this method.

When I call this method in any of the Services I've created for fetching data like this:

handleObjectResponse(serverResponse: response, objectConstructor: ChartData.fromJson); 

I get error: The getter 'fromJson' isn't defined for the class 'ChartData'. Try importing the library that defines 'fromJson', correcting the name to the name of an existing getter, or defining a getter or field named 'fromJson'.

Where I think the problem is is in this model class and factory statement, but I don't know how to fix it:

class ChartData {
  List<ChartDataPoint> points;

  ChartData({
    this.points,
  });

  factory ChartData.fromJson(Map<String, dynamic> json) {
    List jsonPoints = json["data"];
    return ChartData(
        points: List.generate(jsonPoints.length,
        (i) => ChartDataPoint.fromJsonArray(jsonPoints[i])));
  }
}
like image 740
Aleksandar Avatar asked Sep 01 '25 22:09

Aleksandar


1 Answers

You cannot pass constructors as functions. You need to create a function what will call the constructor instead:

(int a) => Foo(a);
like image 190
Rémi Rousselet Avatar answered Sep 03 '25 17:09

Rémi Rousselet