这是否意味着在Dart中(使用“abstract class”)不可能实现此功能,因为静态方法和工厂初始化程序不会从抽象类继承?
我问这个问题是因为我正在编写许多类似的API GET请求方法,这些方法可以很容易地合并成一个,例如:
static Future<T> get<T extends JSONInitializable>(int id) async {
final resourceName = T; // TODO: transform to snake case
final uri = Uri.parse("$kApiHostname/api/$resourceName/$id");
final response = await _secureGet(uri);
if (response == null) {
return null;
}
final responseJson = json.decode(response.body);
final model = T.fromJson(responseJson);
return model;
}
但是为了让它正常工作,我需要将T
限制为一个定义了.fromJson()
初始化程序的协议/接口。