You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中调用Instagram API获取图片列表失败的问题求助

解决Flutter中通过Instagram API获取图片列表的问题

1. 修正API请求的字段参数

你当前仅请求media字段,Instagram Graph API默认只会返回媒体内容的ID集合,无法直接拿到图片的URL等核心信息。需要在fields中指定媒体的子字段,才能获取图片的具体数据:

queryParameters: {
  "fields": "media{id,media_type,media_url,caption,thumbnail_url}",
  "access_token": user!.token,
},
  • media_type:区分内容类型(IMAGE/VIDEO/CAROUSEL_ALBUM),方便筛选纯图片内容
  • media_url:图片或视频的直接访问链接
  • thumbnail_url:视频的缩略图链接(图片类型的话该字段与media_url一致)

2. 确认登录时已申请user_media权限

获取用户媒体内容必须拥有user_media权限,你需要在使用simple_auth配置Instagram登录时,将该权限加入scope列表:

// simple_auth的Instagram配置示例
final instagram = SimpleAuth(
  baseUrl: "https://api.instagram.com/oauth/authorize",
  tokenUrl: "https://api.instagram.com/oauth/access_token",
  clientId: "你的客户端ID",
  scopes: ["user_profile", "user_media"], // 必须包含user_media
);

如果登录时未申请该权限,API会返回权限不足的错误,无法获取媒体列表。

3. 处理媒体内容的分页

当用户的媒体内容较多时,API返回的media数据会被分页,响应体中会包含paging字段,里面的next字段是下一页数据的请求地址。你需要循环请求该地址来获取所有图片:

Future<List<dynamic>> fetchAllMedia(String accessToken) async {
  List<dynamic> allMedia = [];
  String? nextUrl = "https://graph.instagram.com/me?fields=media{id,media_type,media_url}&access_token=$accessToken";

  while (nextUrl != null) {
    final response = await http.get(Uri.parse(nextUrl));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      allMedia.addAll(data['media']['data']);
      nextUrl = data['media']['paging']?['next'];
    } else {
      throw Exception("获取媒体列表失败");
    }
  }
  return allMedia;
}

4. 处理轮播专辑(CAROUSEL_ALBUM)

如果返回的media_type是CAROUSEL_ALBUM,该专辑内的图片无法直接通过media_url获取,需要额外请求专辑子内容接口:

Future<List<dynamic>> fetchCarouselMedia(String mediaId, String accessToken) async {
  final response = await http.get(Uri.parse(
    "https://graph.instagram.com/$mediaId/children?fields=id,media_type,media_url&access_token=$accessToken"
  ));
  if (response.statusCode == 200) {
    return jsonDecode(response.body)['data'];
  } else {
    throw Exception("获取轮播专辑内容失败");
  }
}

内容的提问来源于stack exchange,提问作者Ayaz Nazir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:39:20