如何在Flutter/Dart中获取Google Drive文件夹内文件及下载链接
用Flutter/Dart获取Google Drive文件夹内PDF文件的名称与下载链接
前置准备
- 登录Google Cloud Console,创建新项目并启用Google Drive API
- 创建OAuth 2.0客户端ID(根据应用类型选择桌面/移动/网页类型)
- 在
pubspec.yaml中添加依赖:
dependencies: flutter: sdk: flutter googleapis: ^12.0.0 googleapis_auth: ^1.4.1 http: ^1.1.0
代码实现
1. 初始化Drive API客户端
import 'package:googleapis/drive/v3.dart' as drive; import 'package:googleapis_auth/auth_io.dart'; import 'package:http/http.dart' as http; // 替换为你的OAuth客户端ID和密钥 const _clientId = ClientId('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET'); // 仅请求Drive只读权限 const _scopes = [drive.DriveApi.driveReadonlyScope]; Future<drive.DriveApi> _getDriveClient() async { final authClient = await clientViaUserConsent(_clientId, _scopes, (authUrl) { // Flutter环境下可使用url_launcher打开该链接完成用户授权 print('请访问以下链接完成授权:$authUrl'); print('授权后输入返回的验证码:'); }); return drive.DriveApi(authClient); }
2. 获取指定文件夹内的PDF文件列表
Future<List<Map<String, String>>> fetchPdfFiles(String folderId) async { final driveApi = await _getDriveClient(); // 查询条件:指定文件夹下的PDF文件,排除已删除文件 final query = "'$folderId' in parents and mimeType='application/pdf' and trashed=false"; final fileListResponse = await driveApi.files.list( q: query, fields: 'files(id, name)', // 仅获取必要的文件ID和名称字段 ); final pdfFiles = <Map<String, String>>[]; for (final file in fileListResponse.files ?? []) { // 生成直接下载链接 final downloadUrl = 'https://drive.google.com/uc?export=download&id=${file.id}'; pdfFiles.add({ 'name': file.name ?? '未命名文件', 'downloadUrl': downloadUrl, }); } return pdfFiles; }
3. 调用示例
void main() async { // 替换为目标Google Drive文件夹的ID(从文件夹链接中提取) const targetFolderId = 'YOUR_FOLDER_ID'; try { final pdfFiles = await fetchPdfFiles(targetFolderId); print('文件夹内的PDF文件:'); for (final file in pdfFiles) { print('- 名称:${file['name']}'); print(' 下载链接:${file['downloadUrl']}'); } } catch (e) { print('获取文件失败:$e'); } }
关键注意事项
- 文件夹权限:目标文件夹需设置为公开可访问,或授权的Google账号拥有该文件夹的读取权限
- 文件夹ID提取:从Google Drive文件夹链接中提取ID部分,例如链接
https://drive.google.com/drive/folders/1XyZabcDefGhIjKlMnOpQrStUvW中的1XyZabcDefGhIjKlMnOpQrStUvW即为文件夹ID - OAuth授权:首次运行会要求用户登录Google账号并授权应用访问Drive,授权后会生成持久化凭据(后续运行无需重复授权)
- 依赖版本:若出现版本冲突,可根据当前Dart/Flutter环境调整
pubspec.yaml中的依赖版本号
内容的提问来源于stack exchange,提问作者heyom
相关产品推荐
相关产品推荐

