首页 > 解决方案 > 我不明白如何从 dart 中的 API 获取数据

问题描述

我想从此 api https://invidio.us/api/v1/search?q=获取视频标题和视频 ID

例如,您搜索https://invidio.us/api/v1/search?q=tech+lead

你得到这个json。

[
  {
    "type": "video",
    "title": "\"The Last Programmer\" (hacking the pandemic)",
    "videoId": "heXI1pgQhvY",
    "author": "TechLead",
    "authorId": "UC4xKdmAXFh4ACyhpiQ_3qBw",
    "authorUrl": "/channel/UC4xKdmAXFh4ACyhpiQ_3qBw",
    "videoThumbnails": [...],
    "description": "Ex-Google TechLead hacks into the viral pandemic.  Check out http://coderpro.com/ for 100+ coding interview videos explained ...",
    "descriptionHtml": "<div class=\"yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2\" dir=\"ltr\">Ex-Google TechLead hacks into the viral pandemic.  Check out <a href=\"http://coderpro.com/\" target=\"_blank\" title=\"http://coderpro.com/\" rel=\"nofollow\" dir=\"ltr\" class=\"yt-uix-redirect-link\">http://coderpro.com/</a> for 100+ coding interview videos explained ...</div>",
    "viewCount": 58578,
    "published": 1585252516,
    "publishedText": "1 day ago",
    "lengthSeconds": 447,
    "liveNow": false,
    "paid": false,
    "premium": false
  },
{...},  //other videos.
{...},
...]

我的目标是在 dart/Flutter 中编写一个程序,它将获取每个视频标题及其对应的 videoId 并将它们推送到一个列表中。

我试过在网上搜索如何做到这一点,我遇到了https://flutter.dev/docs/cookbook/networking/fetch-data

但我想做的事情似乎很复杂。我想知道是否存在更简单的方法。还考虑到我最多只需要搜索查询中的前 8 个视频。

标签: flutterdartfetch

解决方案


我相信你是说你不想创建一个类,因为你不需要它。你可以不创建一个,即使它可能更容易出错:

final result = await http.get('https://invidio.us/api/v1/search?q=tech+lead');
final data = json.decode(result.body);
data.forEach((e) {
  print(e['title']);
  print(e['videoId']);
});

推荐阅读