![](/img/trans.png)
[英]How to enforce Implements constraint on generic type T in generic Dart method?
[英]How do i invoke method on a generic type in dart
有幾個模型具有相同的結構,{類型:xxx,設置:xxx},所以我想使用父 class 具有通用類型“T”的“WidgetConfig”來實現這個,但是當我添加“fromJson”時出現問題“ 方法。 我如何調用泛型類型的方法或任何其他方法來實現它?
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
}
}
}
然后我使用摘要 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();
}
}
}
直接顯示function作為參考。
在這里發送 function 作為參考。
FireStoreHelper.getList<ModelLesson>('grade4', ModelLesson.fromJson);
在這里獲取方法。
static Future<List<T>> getList<T>(String path, Function fromJson)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.