flutter 如何在dart中对泛型类型调用方法?

mspsb9vt  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(227)

有几种模型具有相同的结构,{ type:xxx,设置:xxx},所以我想使用一个父类“WidgetConfig”和一个泛型类型“T”来实现这个,但是当我添加“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
    }
  }
}

然后我用了一个抽象类,但是仍然不起作用。

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

code picture

b5buobof

b5buobof1#

直接显示函数作为参考。

此处发送函数作为参考。

FireStoreHelper.getList<ModelLesson>('grade4', ModelLesson.fromJson);

在此处获取方法。

static Future<List<T>> getList<T>(String path, Function fromJson)

相关问题