使用 dart 和 flutter 与 google calendar api 来获取用户日历上的事件列表

2023-12-30

我正在尝试通过重新构建我之前用 Java 编写的应用程序来学习如何使用 dart 和 flutter,其中涉及使用 Google 自己的日历 API 从 Google 日历获取事件。

通过阅读(不是很详细)googleapis_auth 包的文档 https://www.dartdocs.org/documentation/googleapis_auth/0.2.3+6/index.html,以及只有其他线程 https://stackoverflow.com/questions/27235387/using-the-googleapis-library-in-dart-to-update-a-calendar-and-display-it-on-a-we在 StackOverflow 上关于一个非常相似的问题,我设法将理论上应该有效的代码放在一起:

import 'package:googleapis/calendar/v3.dart';
import 'package:googleapis_auth/auth_io.dart';

//get Service Account Credentials
final accountCredentials = new ServiceAccountCredentials.fromJson({
  "private_key_id": "myprivatekeyid",
  "private_key": "myprivatekey",
  "client_email": "myclientemail",
  "client_id": "myclientid",
  "type": "service_account"
});
var _scopes = [CalendarApi.CalendarScope]; //defines the scopes for the calendar api

void getCalendarEvents() { 
    clientViaServiceAccount(accountCredentials, _scopes).then((client) {
      var calendar = new CalendarApi(client);
      var calEvents = calendar.events.list("primary");
      calEvents.then((Events events) {
        events.items.forEach((Event event) {print(event.summary);});
      });
    });
}

上面的代码在模拟器上运行时不会产生任何错误,也不会在控制台中打印任何事件摘要。但当查看项目的仪表板时,请求通过响应代码 200,也称为成功。我还尝试使用嵌套在 clientViaServiceAccount 中的类似代码来获取所有日历的 id,但它也不会返回任何内容。

另外,从文档中我发现访问 API 的最简单方法是通过客户端服务帐户(如代码中所示),而不是通过我更习惯的 OAuth2 客户端 ID。

我错过了什么吗?代码有错吗?也许我需要弄乱服务帐户上的设置?任何帮助,将不胜感激。


我能够使用您的代码进行一次更改(第 6 步)。首先,确保服务器端设置正确(步骤 1-5)。
谷歌开发者控制台
1.创建项目
2.启用日历API
3.创建服务帐户-下载json凭证
谷歌日历设置
4.与特定人员共享-添加服务帐户的电子邮件
5. 复制日历 ID ([电子邮件受保护] /cdn-cgi/l/email-protection)
你的代码
6. 将“主要”替换为步骤 5 中的日历 ID

有关步骤 1-5 的详细概述,请参见https://murze.be/how-to-setup-and-use-the-google-calendar-api https://murze.be/how-to-setup-and-use-the-google-calendar-api。它们适用于 PHP,但 Google 端的设置是相同的。

希望这对某人有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 dart 和 flutter 与 google calendar api 来获取用户日历上的事件列表 的相关文章

随机推荐