【发布时间】: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 之外的列表是空的