【问题标题】:How to fetch api data by passing variables (parameters)?如何通过传递变量(参数)来获取api数据?
【发布时间】:2019-05-25 11:11:19
【问题描述】:

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

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

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

获取 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 sn-p 是:

{ “PID”:1111, "国家": "澳大利亚", "profile": "\n\n 废话", "imageURL": "https://www.cricapi.com/playerpic/1111.jpg",

我想要实现的是,动态显示多个玩家资料,而不是在代码中传递硬编码的pid,以便 UI 将在listview 中显示多个玩家。

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

【问题讨论】:

    标签: json flutter flutter-layout


    【解决方案1】:

    通过使用String 插值并接收 id 作为参数。你可以阅读更多关于它的信息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'];
    

    【讨论】:

    • 感谢您的解决方案。我在initState() 中将FetchJson() 称为void initState() { int pid; FetchJson(pid); }。这会引发错误:NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("batting")。我知道 ['data'] 不知何故是null,但不确定它是如何突然开始抛出此错误的。完整的代码在这里:pastebin.com/q5zEPmiw。 @miguelpruivo
    • 我在实施我提出新问题的解决方案时偶然发现了一个障碍。
    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多