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

Flutter中Google Drive API上传文件后获取文件ID失败求助

解决Flutter中Google Drive上传后无法获取文件ID的问题

问题原因

你的gDriveFileCreator函数返回类型是dynamic,导致responsePdfUpload的类型被模糊推断——Dart里同时存在dart:io.File和googledrive.File两个类,调用getId()时,程序误把返回对象当成了dart:io.File(这个类没有getId()方法),所以抛出异常,哪怕调试时能看到ID字段。

解决方案

明确指定函数返回类型为googledrive.File,同时在调用时也声明变量类型,彻底避免类型混淆:

  1. 修改上传函数的返回类型:
// 将返回类型从dynamic改为googledrive.File
Future<googledrive.File> gDriveFileCreator(googledrive.DriveApi drive,
      googledrive.File fileToUpload, String path) async {
    File file = File(path);
    fileToUpload.name = p.basename(file.absolute.path);
    var response = await drive.files.create(
      fileToUpload,
      uploadMedia: googledrive.Media(file.openRead(), file.lengthSync()),
    );
    return response;
  }
  1. 调用时指定变量类型:
// 明确声明responsePdfUpload为googledrive.File类型
googledrive.File responsePdfUpload =
              await gDriveFileCreator(drive, fileToUpload, pdfPath!);

// 现在可以正常获取ID,根据SDK版本选择方式:
// 方式1:直接访问id属性(部分新版本SDK)
String fileId = responsePdfUpload.id!;
// 方式2:调用getId()方法(旧版本SDK)
String fileId = responsePdfUpload.getId();

这样就能保证操作的是Google Drive的File实例,顺利获取到文件ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:20:32