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

如何在Flutter应用中通过YouTube API获取私有及未列出视频

通过YouTube API获取私有/未列出视频(Flutter环境)

1. 确认认证与权限配置

  • 必须使用OAuth 2.0认证,API Key无法访问私有/未列出内容。推荐用Flutter的google_sign_in包完成用户授权流程。
  • 申请OAuth时,必须包含以下scope之一:
    • https://www.googleapis.com/auth/youtube.readonly(仅需读取视频时用这个)
    • https://www.googleapis.com/auth/youtube(需要修改视频时用)
  • 注意:服务账号无法访问个人YouTube账号的私有视频,必须走用户授权流程。

2. 调用YouTube Data API的videos.list接口

核心是通过该接口筛选当前授权用户的视频,指定隐私状态过滤条件:

  • 关键参数:
    • part:必填,至少指定snippet,status(要获取视频基本信息和隐私状态)
    • mine:设为true,表示获取当前授权用户的视频
    • maxResults:可选,控制每页返回的视频数量(最大50)
    • pageToken:可选,用于分页加载更多视频
    • 过滤隐私状态:可以在请求参数中加入privacyStatus=private,unlisted(用逗号分隔多个状态)

Flutter中用http包的示例代码:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<List<dynamic>> getPrivateUnlistedVideos(String accessToken) async {
  final url = Uri.https('www.googleapis.com', '/youtube/v3/videos', {
    'part': 'snippet,status',
    'mine': 'true',
    'privacyStatus': 'private,unlisted',
    'maxResults': '50',
  });

  final response = await http.get(
    url,
    headers: {'Authorization': 'Bearer $accessToken'},
  );

  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    return data['items'] ?? [];
  } else {
    throw Exception('Failed to load videos: ${response.body}');
  }
}

3. 处理分页加载

如果视频数量超过maxResults,接口会返回nextPageToken,需要循环请求直到没有该字段:

Future<List<dynamic>> getAllPrivateUnlistedVideos(String accessToken) async {
  List<dynamic> allVideos = [];
  String? nextPageToken;

  do {
    final url = Uri.https('www.googleapis.com', '/youtube/v3/videos', {
      'part': 'snippet,status',
      'mine': 'true',
      'privacyStatus': 'private,unlisted',
      'maxResults': '50',
      if (nextPageToken != null) 'pageToken': nextPageToken,
    });

    final response = await http.get(
      url,
      headers: {'Authorization': 'Bearer $accessToken'},
    );

    if (response.statusCode != 200) {
      throw Exception('Failed to load videos: ${response.body}');
    }

    final data = json.decode(response.body);
    allVideos.addAll(data['items'] ?? []);
    nextPageToken = data['nextPageToken'];
  } while (nextPageToken != null);

  return allVideos;
}

4. 常见问题排查

  • 403权限错误:检查OAuth scope是否包含youtube.readonly或youtube,且用户授权时允许了该权限。
  • token过期:用google_sign_in包可以自动刷新access token,避免手动处理过期问题。
  • 无视频返回:确认授权的账号确实有私有/未列出视频,且请求参数中mine=true正确设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:01:09