Flutter 颤振通用RESTAPI调用函数
我正在开发我的第一个颤振应用程序。调用rest api并返回结果所需的应用程序。我希望创建Flutter 颤振通用RESTAPI调用函数,flutter,dart,Flutter,Dart,我正在开发我的第一个颤振应用程序。调用rest api并返回结果所需的应用程序。我希望创建generic函数来调用RESTAPI。我已经写了下面的代码,但我并没有轻描淡写,我如何才能解码特定模型中的api响应 Future<T> apiRequest<T>( String endPoint, RequestMethod method, { String body = '', String token = '', }) async {
generic
函数来调用RESTAPI。我已经写了下面的代码,但我并没有轻描淡写,我如何才能解码特定模型中的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();
}
}
如何解码body
json.decode(resp.body)
到类型为T
?的GenericResp
,您可以添加一个泛型参数,将json数据反序列化到GenericResp
。诸如此类:
Future<T> apiRequest<T>(
String endPoint,
RequestMethod method, T Function(Object json) fromJson, {
String body = '',
String token = '',
}) async { ... }
然后一个电话会是这样的:
await ApiService.newInstance(context).apiRequest<GenericResp>('/api/people',
RequestMethod.get, (json) => GenericResp.fromJson(json));
wait-ApiService.newInstance(context).apirest('/api/people',
RequestMethod.get,(json)=>GenericResp.fromJson(json));
无法理解您对t类型的GenericResp所说的话,GenericResp已经是一个类了
?
Future<T> apiRequest<T>(
String endPoint,
RequestMethod method, T Function(Object json) fromJson, {
String body = '',
String token = '',
}) async { ... }
if (resp != null && this.validateResponse(resp)) {
return fromJson(json.decode(resp.body));
}
await ApiService.newInstance(context).apiRequest<GenericResp>('/api/people',
RequestMethod.get, (json) => GenericResp.fromJson(json));