【发布时间】:2021-10-20 17:58:17
【问题描述】:
据我了解,可以使用 REST 方法通过 HTTP 调用和处理 CRUD 操作。我的目标是通过 [POST, GET, PUT, DELETE] 管理大约 5 个实体的 CRUD 事务。总的来说,即使我可以在辅助函数中重用一些样板,我也必须编写 20 个不同的原型。
我想减少泛型类型的代码量。这是我的想法:
abstract class RestResource
{
int id;
static String name = "";
RestResource({required this.id});
Map<String, dynamic> toJson() => throw UnimplementedError();
factory RestResource.fromJson(Map<String, dynamic> json) => throw UnimplementedError();
}
class ActualResource extends ResourceRest
{
final String additional;
static String name = "resource";
ActualResource({required this.additional, required int id}) : super(id: id);
@override
Map<String, dynamic> toJson() {
// return serialized
};
@override
factory RestResource.fromJson(Map<String, dynamic> json) {
// create object from json
};
}
// Example for GET request for a resource with an id ex: api/resource/1234
Future<Resource> fetch<Resource extends RestResource>(int id) async {
Uri url = Uri.http('http://www.someurl.com/api/', Resource.name + id.toString());
http.Response res = await _httpClient.get(url);
validateHTTPResponse(res);
return Resource.fromJson(convert.jsonDecode(res.body));
}
// This is how I'd want to call it
int id = 1234;
ActualResource r = await fetch<ActualResource>(id);
我的问题。
Resource 是一个泛型类型,即使它扩展了 RestResource 的定义。调用工厂方法Resource.fromJson 会触发以下智能感知错误。
关于资源名称
The getter 'name' isn't defined for the type 'Type'.
Try importing the library that defines 'name', correcting the name to the name of an existing getter, or defining a getter or field named 'name'.
关于 Resource.fromJson
The method 'fromJson' isn't defined for the type 'Type'.
Try correcting the name to the name of an existing method, or defining a method named 'fromJson'
我想开始讨论开发人员如何做这样的事情,因为它可以节省大量的时间和精力。
【问题讨论】: