问题
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