本文介绍了如何通过传递变量(参数)来获取api数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取体育运动员的api数据,我需要为其传递唯一的player id.目前,我必须手动传递pid,一次只能获取一个玩家的数据.但是我想获取多个玩家数据并将其显示在listView中.

I am fetching api data for sports player for which I need to pass unique player id. Currently, I have to pass pid manually which fetches only one player's data at a time. But I would like to fetch multiple players data and display it in listView.

API端点为: https://cricapi.com/api/playerStats ?apikey =& pid = 0000 .

我能够解析上述url,获取结果并正确显示在UI中,但我想获取多个玩家数据,而不仅仅是一个.

I am able to parse above url, fetch it's result and display in UI properly, but I want to fetch multiple players data and not just one.

要获取api的代码:

FetchJson() async {
  var response = await http.get('https://cricapi.com/api/playerStats?
    apikey=&pid=1111');

  if (response.statusCode == 200) {
    String responseBody = response.body;
    var responseJson = jsonDecode(responseBody);
    name = responseJson['name'];
    playingRole = responseJson['playingRole'];
    battingStyle = responseJson['battingStyle'];
    country = responseJson['country'];
    imageURL = responseJson['imageURL'];

Json代码段是:

我想要实现的是,动态显示多个玩家配置文件,而不是在代码中传递硬编码的pid,以便用户界面将在listview中显示多个玩家.

What I am trying to achieve is, to display multiple players profile dynamically instead of passing hardcoded pid in the code, so that the UI will display multiple players in listview.

如何在url端点中动态传递不同的pid?

How to pass different pid dynamically in the url endpoint ?

推荐答案

通过使用String插值并接收id作为参数.您可以在此处了解更多信息.

By using String interpolation and receiving the id as parameter. You can read more about it here.

FetchJson(int playerId) async {
  var response = await http.get('https://cricapi.com/api/playerStats?
    apikey=&pid=$playerId');

  if (response.statusCode == 200) {
    String responseBody = response.body;
    var responseJson = jsonDecode(responseBody);
    name = responseJson['name'];
    playingRole = responseJson['playingRole'];
    battingStyle = responseJson['battingStyle'];
    country = responseJson['country'];
    imageURL = responseJson['imageURL'];

这篇关于如何通过传递变量(参数)来获取api数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 17:31