如何在变量中使用Class?

How to use Class in variable?

我想按如下方式转换获取的数据,但出现错误并且模拟器关闭! 我能做什么?

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

这里是classResponseCompany.dart

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

这里是ResponseCompany.g.dart

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

恕我直言 item.value.fromJson 将不起作用。由于 fromJson 是工厂构造函数,并且在 dart 的规则中,不能为存储在变量中的类型调用工厂构造函数。 (实际上,问题是隐藏的,因为您创建了一个 Map<string, dynamic> 并且 dart 允许在编译时在 dynamic 上调用所有内容。)

针对您的具体情况,您可以这样做

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