【问题标题】:Flutter - Multiple HTTP Requests to the same JSONFlutter - 对同一个 JSON 的多个 HTTP 请求
【发布时间】:2021-05-24 02:40:39
【问题描述】:

我有这个 API 可以用来获取数据。
对于每个“日期”,我都有一个 JSON 对象。
我想做的是从假设 5 年中获取对象,并在相同的最终 JSON http 响应中获取它们。 所以我不必只显示一天。

Future<List<Schedule>> getFromEspnSchedule(String sport) async {
  final url = 'http://myserver.com/api/$date'; //the $date would be e.g. 2010, 2011, 2012, ...
  final response = await http.get(url);

  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((data) {
      return new Schedule.fromJson(data);
    }).toList();
  } 
}

实现这一点的最佳方法是什么?

【问题讨论】:

    标签: json rest flutter


    【解决方案1】:

    如果您的 API 仅返回一个 Schedule 对象,您需要修改方法以获取单个元素。

    Future<Schedule> getFromEspnSchedule(String sport) async {
      final url = 'http://myserver.com/api/$date';
      final response = await http.get(url);
    
      if (response.statusCode == 200) {
        return Schedule.fromJson(json.decode(response.body));
      } else {
        // make sure you return API error here
      }
    }
    

    完成此操作后,您可以继续将其链接到同时进行的多个调用中,以更快地获取数据:

    List<Schedule> responseList = await Future.wait([
      getFromEspnSchedule('football'),
      getFromEspnSchedule('volleyball'),
      getFromEspnSchedule('basketball'),
      getFromEspnSchedule('chess'),
    ]);
    
    // responseList objects are listed the same way they are called above.
    Schedule footballSchedule = responseList[0];
    Schedule volleyballSchedule = responseList[1];
    Schedule basketballSchedule = responseList[2];
    Schedule chessSchedule = responseList[3];
    

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多