【问题标题】:I'm adding the data from the json file to my list, but the list is empty我正在将 json 文件中的数据添加到我的列表中,但列表为空
【发布时间】:2021-07-06 02:13:29
【问题描述】:

我正在从 API 中提取 json 文件并尝试将其添加到列表中,但之后列表为空。

Future<List<Posts>> getPosts() async {
    var datas = await http.get(
        Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));

    var jsonDatas = json.decode(datas.body);

    List<Posts> postList = [];

    for (int i = 0; i < 7; i++) {
      var postJson = jsonDatas["data"]["children"][i];

      String subreddit = postJson["data"]["subreddit"];
      String title = postJson["data"]["title"];
      String thumbnail = postJson["data"]["thumbnail"];

      Posts post = Posts(title, thumbnail, subreddit);

      postList.add(post);
    }

    print(postList.length);

    return postList;
  }

【问题讨论】:

  • 尝试打印 subreddit 、标题和缩略图
  • 我在 for 中得到了正确的输出,但是 for 之外的列表是空的

标签: json flutter dart future


【解决方案1】:

因此,当我最终尝试此操作时,出现范围错误。不确定 7 在你的 for 循环中来自哪里,但在响应中使用 children 的长度可能更安全。当我查看 json 响应时,您尝试解析的内容只有 5 项。

也许情况会改变,但更有理由不在循环中使用固定数字。

这对我有用。

Future<List<Posts>> getPosts() async {
    var datas = await http.get(
        Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));

    var jsonDatas = json.decode(datas.body);

    List<Posts> postList = [];

    // this is the actual length of what you're trying to parse
    final responseLength = jsonDatas["data"]["children"].length as int;

    for (int i = 0; i < responseLength; i++) {
      var postJson = jsonDatas["data"]["children"][i];

      String subreddit = postJson["data"]["subreddit"];
      String title = postJson["data"]["title"];
      String thumbnail = postJson["data"]["thumbnail"];

      Posts post = Posts(title, thumbnail, subreddit);

      postList.add(post);
    }

    print(postList.length);

    return postList;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多