How to fetch api data by passing variables (parameters)?

坚强是说给别人听的谎言 提交于 2019-12-11 08:56:05

问题


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 endpoint is: https://cricapi.com/api/playerStats?apikey=&pid=0000.

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.

Code to fetch 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 snippet is:

{ "pid": 1111, "country": "Australia", "profile": "\n\n blah", "imageURL": "https://www.cricapi.com/playerpic/1111.jpg",

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.

How to pass different pid dynamically in the url endpoint ?


回答1:


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'];


来源:https://stackoverflow.com/questions/53944759/how-to-fetch-api-data-by-passing-variables-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!