首页 > 解决方案 > 在 Flutter 中,如何通过文档 ID 访问 Google Docs 文档?

问题描述

背景

在 Google Apps 脚本中,我可以通过调用 DocumentApp 并使用 openById 方法来访问 Google Drive 中的现有文档。例如:

var documentToAccess = DocumentApp.openById(documentId);

同样,我可以通过调用 DriveApp.getFileById 访问 Google Drive 中的文件。例如:

var fileToAccess = DriveApp.getFileById(documentId);

问题

在 Flutter 中,googleapis 依赖项允许我导入多个库,包括 googleapis/drive/v3.dart、googleapis/docs/v1.dart 和 googleapis/file/v1.dart,它们提供了访问 Google Drive 中文件属性的方法,但我似乎找不到一种方法来实际获取或打开我想要处理的文件。

问题

在 Flutter 中,如何通过文档 ID 获取 Google Docs 文档,以便我可以处理该文档?

googleapis 文档和其他尝试

googleapis 文档有一些有用的资源,但尽管尝试实现这些资源,但我似乎无法得到我需要的东西。例如:

var fileToAccess = DriveApi().files.get('documentId’);
var fileToAccess = Document().documentId;
var fileToAccess = FilesResourceApi().get('documentId');

标签: flutterdartgoogle-apigoogle-drive-api

解决方案


看起来用户没有登录,所以首先,登录用户。

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/documents.readonly',
    'https://www.googleapis.com/auth/drive.readonly'
  ],
);

要实例化客户端,您将添加如下内容:

 final client = MyClient(defaultHeaders: {
      'Authorization': 'Bearer ${authentication.accessToken}'
    });

然后您尝试获取文档的位置:

DriveApi driveApi = DriveApi(client);
    var files = await driveApi.files
        .list(q: 'mimeType=\'application/vnd.google-apps.document\'');

推荐阅读