首页 > 解决方案 > 我正在将 json 文件中的数据添加到我的列表中,但列表为空

问题描述

我正在从 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;
  }

标签: jsonflutterdartfuture

解决方案


所以当我最后尝试这个时,我得到了一个范围错误。不确定 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;
  }

推荐阅读