繁体   English   中英

我如何在 dart 中调用泛型类型的方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM