Passing constructor as argument in Flutter

3,151

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

(int a) => Foo(a);
Share:
3,151
Aleksandar
Author by

Aleksandar

Experienced mobile technical team lead with more than 3 years of experience in leading small and mid scale teams including software engineers and software testers. iOS and Flutter Developer with a demonstrated history of working in the information technology and services industry. Skilled in both Objective-C and Swift with background in Android development. Strong engineering professional with a Master's Degree focused in Electrical and Computer Engineering from Faculty Of Technical Science in Novi Sad.

Updated on December 13, 2022

Comments

  • Aleksandar
    Aleksandar over 1 year

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