我的Flutter应用程序中有API通讯服务,其中包含10多种不同的服务,以及100多个需要解析数据的API调用。为了重用代码,我决定创建一些常见的解析代码,以解析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);
}
}
这样,无论Object类是什么,只要将构造函数传递给此方法,我就可以以可重用的方式从API解析JSON对象。
当我在为获取数据而创建的任何服务中调用此方法时,如下所示:
handleObjectResponse(serverResponse: response, objectConstructor: ChartData.fromJson);
我得到错误: 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'.
我认为问题出在此模型类和factory
语句中,但我不知道如何解决:
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])));
}
}
您不能将构造函数作为函数传递。您需要创建一个将调用构造函数的函数:
(int a) => Foo(a);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句