Dart, Can't call Generic's method
You cannot call static methods on type variables. Static methods must be known at compile-time, and the value of a type variable is not known until run-time.
You can parameterize your class with the method that you want to call:
class DataList<T> { final bool success; dynamic data; T dynamic Function(Object) fromJson; DataList({ this.success, List<dynamic> data, this.fromJson; }) { castDataToList(data); } factory DataList.fromJson(Map<String, dynamic> json, T fromJson(Object o)) { return DataList( success: json['success'], data: json['data'], fromJson: fromJson, ); } void castDataToList(jsonData) { this.data = List<T>.from(jsonData.map((x) => fromJson(x))); }}
When you want to use the class with a type, Foo
which has a fromJson
static method, you create the instance as:
var dataList = DataList<Foo>fromJson(someJsonMap, Foo.fromJson);
This passes the Foo.fromjson
function to the class, which can then use it when needed.