我有一个 Flutter 应用程序,已添加日历,并且我想将日历事件添加到用户的网络 Google 日历中。我正在使用 Google Calendar API 来执行此操作。
当我运行代码并尝试将事件添加到日历时,没有任何反应。当我通过调试器时,我没有收到任何错误。
这是代码:
class CalendarClient {
static const _scopes = [CalendarApi.calendarScope];
insert(title, eventDate, startTime, endTime) {
var clientID;
if (kIsWeb) {
clientID = ClientId("<my client ID here>.apps.googleusercontent.com","");
} else {
/// Android
clientID = ClientId("<my client ID here>.apps.googleusercontent.com","");
}
clientViaUserConsent(clientID, _scopes, prompt).then((AuthClient client) {
var calendar = CalendarApi(client);
calendar.calendarList
.list()
.then((value) => debugPrint("VAL________$value"));
String calendarId = "primary";
Event event = Event(); // Create object of event
event.summary = title;
EventDateTime start = EventDateTime();
start.dateTime = startTime;
start.timeZone = "GMT+05:00";
event.start = start;
EventDateTime end = EventDateTime();
end.timeZone = "GMT+05:00";
end.dateTime = endTime;
event.end = end;
try {
calendar.events.insert(event, calendarId).then((value) {
debugPrint("ADDEDDD_________________${value.status}");
if (value.status == "confirmed") {
log('Event added in google calendar');
} else {
log("Unable to add event in google calendar");
}
});
} catch (e) {
log('Error creating event $e');
}
});
}
void prompt(String url) async {
debugPrint("Please go to the following URL and grant access:");
debugPrint(" => $url");
debugPrint("");
if (await canLaunchUrl(url as Uri)) {
await launchUrl(url as Uri);
} else {
throw 'Could not launch $url';
}
}
}
我尝试在 Chrome 浏览器和 Android 设备上运行它,但都不起作用。它从不要求我访问,并且在调试器中我不会越过这一行:
clientViaUserConsent(clientID, _scopes, prompt).then((AuthClient client) {
我已经在该行之后的线上放置了断点,它永远不会到达那里,但没有错误。
我做错了什么? 谢谢你的帮助
1。检查客户端 ID 配置:
CalendarApi.calendarScope
)。2。确保正确初始化:
clientViaUserConsent
之前,请确保所有必要的信息
初始化已完成,如 googleapis_auth
包和任何
其他所需配置。3.网络特定问题:
对于网络,同意流程通常会打开一个新窗口。确保您的 浏览器允许弹出窗口,并且没有任何东西可以阻止此操作。
对于 Web,您可能还想尝试在中添加正确的重定向 URI 您的 Google Cloud Console 在“OAuth 2.0 客户端 ID”下。
4。在
try-catch
周围使用 clientViaUserConsent
:
try {
clientViaUserConsent(clientID, _scopes, prompt).then((AuthClient client)
{
// Rest of your code
});
} catch (e) {
log('Error during OAuth consent: $e');
}
5。调试提示方法: 确保提示方法正确启动 URL。如果没有,请考虑使用不同的方法打开 URL,例如 url_launcher,并调试 URL 是否正确传递。
6。检查 OAuth 2.0 重定向:
确保在 Google API 控制台中正确配置重定向 URI。 对于 Web,重定向 URI 应与您为 Flutter Web 应用提供服务的域相匹配。
7。控制台日志:
在关键步骤之前和之后添加更多调试日志,尤其是在 OAuth2 流程周围,以确定流程停止的位置。
8。使用新项目进行测试:
有时配置问题很难查明。尝试使用最少的代码设置一个新项目,仅处理 OAuth2 和 Google Calendar API 集成。这可以帮助隔离问题。