[英]How do i invoke method on a generic type in dart
There are several models have a same structure, { type: xxx, settings: xxx}, so i would like to use a parent class "WidgetConfig" with a generic type "T" to implement this, but problem occurs when i add "fromJson" methods.有几个模型具有相同的结构,{类型:xxx,设置:xxx},所以我想使用父 class 具有通用类型“T”的“WidgetConfig”来实现这个,但是当我添加“fromJson”时出现问题“ 方法。 How can i invoke method on a generic type or any other ways to implement this?我如何调用泛型类型的方法或任何其他方法来实现它?
class BannerWidgetViewModel extends ChangeNotifier {
WidgetConfig<BannerWidgetConfig> config;
BannerWidgetViewModel(String configJson){
config = WidgetConfig.fromJson(configJson);
}
}
class BannerWidgetConfig {
String imgUrl;
String padImgUrl;
String lessonId;
BannerWidgetConfig.fromJson(json){
if (json != null) {
this.imgUrl = json['imgUrl'];
this.padImgUrl = json['padImgUrl'];
this.lessonId = json['lessonId'];
}
}
}
class WidgetConfig<T> {
WidgetType type;
WidgetConfig.fromJson(json){
if (json != null) {
this.type = json['type'];
// this.settings = T.fromJson(json['settings']); // T doesn't have fromJson method
}
}
}
then i use a abstract class but still not working.然后我使用摘要 class 但仍然无法正常工作。
abstract class BaseWidgetConfig {
BaseWidgetConfig.fromJson(dynamic json);
}
class WidgetConfig<T extends BaseWidgetConfig> {
WidgetType type;
T settings;
WidgetConfig.fromJson(json){
if (json != null) {
this.type = json['type'];
this.settings = T.fromJson();
}
}
}
Directly show the function as a reference.直接显示function作为参考。
send function as a reference here.在这里发送 function 作为参考。
FireStoreHelper.getList<ModelLesson>('grade4', ModelLesson.fromJson);
get the method here.在这里获取方法。
static Future<List<T>> getList<T>(String path, Function fromJson)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.