Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dart and flutter with google calendar api to get a list of events on the a user's calendar

I am trying to learn how to use dart and flutter by re-building an app I've previously coded in Java, which involves getting events from a Google Calendar using Google's own Calendar API.

By reading (a not very detailed) documentation on the googleapis_auth package, as well as the only other thread here on StackOverflow about a very similar issue, I've managed to throw together the code that should theoretically work:

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);});
      });
    });
}

The above code doesn't produce any errors while running it on an emulator, nor does it print any of the event summaries in the console. But when looking on the project's dashboard, the request comes through with response code 200, aka as a success. I have also tried using a similar code nested in the clientViaServiceAccount, to get the ids of all of my calendars, and it also doesn't return anything.

Also, from the documentation I've found that the simplest way to access the API is trough the client service account, as seen in the code, and not through OAuth2 client ID, which I'm more used to.

Am I missing something? Is the code wrong? Maybe I need to mess with the settings on the service account? Any help would be appreciated.

like image 343
Evgeny Astapov Avatar asked Mar 07 '23 14:03

Evgeny Astapov


1 Answers

I was able to get this working using your code with one change (step 6). First, ensure server-side is correctly setup (steps 1-5).
Google Developer Console
1. create project
2. enable calendar api
3. create service account - download json credentials
Google Calendar Settings
4. share with specific people - add email of service account
5. copy Calendar ID ([email protected])
Your Code
6. replace "primary" with Calendar ID from step 5

There's a well-done overview of steps 1-5 at https://murze.be/how-to-setup-and-use-the-google-calendar-api. They are for PHP, but the Google-side setup is the same.

Hope this helps someone.

like image 155
Bryon Nicoson Avatar answered Mar 09 '23 15:03

Bryon Nicoson