【问题标题】:Flutter generic REST API call functionFlutter 通用 REST API 调用函数
【发布时间】:2021-03-04 16:31:43
【问题描述】:

我正在开发我的第一个颤振应用程序。应用程序需要调用 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();
    }
  }

下面是我可以用来调用rest api的代码

await ApiService.newInstance(context)
          .apiRequest<GenericResp>('/api/people', RequestMethod.get);

这是我的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;
  }
}

如何将json.decode(resp.body); 的正文解码为T 类型的GenericResp

【问题讨论】:

  • 无法理解to GenericResp of type T 这一行的意思?GenericResp 已经是class 了?

标签: flutter dart


【解决方案1】:

您可以添加一个通用参数,将您的 json 数据反序列化为 GenericResp。类似的东西:

Future<T> apiRequest<T>(
    String endPoint,
    RequestMethod method, T Function(Object json) fromJson, {
      String body = '',
      String token = '',
    }) async { ... }

在 json 解码后,您将使用 fromJson 参数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    相关资源
    最近更新 更多