Search code examples
flutterclass-eval

How to use Class in variable?


I want to convert fetched data as below, but I got error and emulator shutdown! What can I do?

Map<String, dynamic> responseClassMap = {
'$ResponseCompany': ResponseCompany,//ResponseCompany is class
'$ResponseCompanyDetail': ResponseCompanyDetail, //ResponseCompanyDetail is class
};
for (var item in responseClassMap.entries) {
  if (className == item.key) {
    result = responseData.map((data) => item.value.fromJson(data)).toList();
  }
}

Here is class ResponseCompany.dart

@JsonSerializable()
class ResponseCompany {
final num sales, ...;
...
factory ResponseCompany.fromJson(Map<String, dynamic> json) => _$ResponseCompanyFromJson(json);
...

Here is ResponseCompany.g.dart

ResponseCompany _$ResponseCompanyFromJson(Map<String, dynamic> json) {
  return ResponseCompany(
  );
  ...
}

Solution

  • IMHO item.value.fromJson will not work. Since fromJson is a factory constructor, and in dart's rule, one cannot call factory constructor for a type stored in a variable. (Indeed, the problem is hidden because you create a Map<string, dynamic> and dart allow everything to be called on dynamic at compile time.)

    For your specific case, you can do

    Map<String, dynamic> map = {
    '$ResponseCompany': (d)=>ResponseCompany.fromJson(d),//ResponseCompany is class
    '$ResponseCompanyDetail': (d)=>ResponseCompanyDetail.fromJson(d), //ResponseCompanyDetail is class
    };
    for (var item in map.entries) {
      if (className == item.key) {
        result = responseData.map((data) => item.value(data)).toList();
      }
    }