我首先在我的颤振应用程序上工作。调用rest api并返回结果所需的应用程序。我正在寻找创建generic函数来调用rest api。我写了下面的代码,但我并没有低估,我如何在特定模型中解码 api 响应。
Future<T> apiRequest<T>(
String endPoint,
RequestMethod method, {
String body = '',
String token = '',
}) async {
http.Response resp;
final String url = LocalConstants.apiBaseUrl + endPoint;
final Map<String, String> headers = new Map<String, String>();
headers.putIfAbsent(
HttpHeaders.contentTypeHeader, () => 'application/json');
if (token != null && token.isNotEmpty) {
headers.putIfAbsent(
HttpHeaders.authorizationHeader, () => 'Bearer ' + token);
}
try {
if (method == RequestMethod.get) {
resp = await http.get(
url,
headers: headers,
);
} else if (method == RequestMethod.put) {
resp = await http.put(
url,
headers: headers,
body: body,
);
} else if (method == RequestMethod.post) {
resp = await http.post(
url,
headers: headers,
body: body,
);
} else if (method == RequestMethod.delete) {
resp = await http.delete(
url,
headers: headers,
);
}
if (resp != null && this.validateResponse(resp)) {
return json.decode(resp.body);
}
// else {
// Response resp = new Response();
// resp.respMsg = LocalConstants.genericError;
// resp.respCode = LocalConstants.resp_failure;
// Response.
// }
} on TimeoutException catch (e) {
//handleTimeout();
} on SocketException catch (e) {
print('Socket Error: $e');
//handleTimeout();
} on Error catch (e) {
print('General Error: $e');
//showError();
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我可以用来调用rest api的代码
await ApiService.newInstance(context)
.apiRequest<GenericResp>('/api/people', RequestMethod.get);
Run Code Online (Sandbox Code Playgroud)
这是我的GenericResp课
import 'package:project/models/Response.dart';
class GenericResp extends Response {
int id;
int otherId;
String mappingId;
GenericResp({
this.id,
this.otherId,
this.mappingId,
});
GenericResp.fromJson(Map<String, dynamic> json) {
id = json['id'];
otherId = json['other_id'];
mappingId = json['mapping_id'];
respCode = json['resp_code'];
respMsg = json['resp_msg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = this.id;
data['other_id'] = this.otherId;
data['mapping_id'] = this.mappingId;
data['resp_code'] = this.respCode;
data['resp_msg'] = this.respMsg;
return data;
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能解码身体json.decode(resp.body);到 GenericResp类型的T?
您可以添加一个通用参数,将您的 json 数据反序列化为GenericResp. 类似的东西:
Future<T> apiRequest<T>(
String endPoint,
RequestMethod method, T Function(Object json) fromJson, {
String body = '',
String token = '',
}) async { ... }
Run Code Online (Sandbox Code Playgroud)
在 json 解码后,您将使用fromJson参数:
if (resp != null && this.validateResponse(resp)) {
return fromJson(json.decode(resp.body));
}
Run Code Online (Sandbox Code Playgroud)
然后一个电话看起来像这样:
await ApiService.newInstance(context).apiRequest<GenericResp>('/api/people',
RequestMethod.get, (json) => GenericResp.fromJson(json));
Run Code Online (Sandbox Code Playgroud)