Introduction

In this blog we are going to use Google Calender API with flutter to create an event in google calender. We are going to build a simple flutter app in which there will be a date picker and an input field for adding name for the event. The app will automatically add the event in google calender using the Calender API.

Steps :-

  1. Go to the Google API Dashboard (https://console.cloud.google.com/apis/dashboard)

  2. Sign in with your gmail.

  3. You will see an interface like this. Click on My Project

    alt All your projects should be listed here

  4. Create a new project

    alt

  5. Add your project name and create a new project

    alt

  6. Return to the desktop and open your newly created project from the list.

  7. Click on Enable Api and Services from the menu

    alt

  8. Click on ENABLE API AND SERVICES

    alt

  9. Search for the Google Calender API and enable it. Now return to the Dashboard.

  10. Now go the the OAuth Consent Secrren and choose External. Choosing external will allow any user that you will add further in the test users section to test the app

    alt

  11. Now add necessary information and click on continue

  12. Now click on Add or Remove scopes and add Google Calender API in the scope and click on update

    alt

  13. In the next section add test users and click on save and continue. Review your OAuth Consent summary and continue

    alt


  14. Create a new flutter project using the command

    flutter create myapp
    
  15. Now we have to create OAuth Client ID. Go to the credentials section click on Create Credentials.

    alt

  16. Click on OAuth client ID

    alt

  17. Select Application type to android and fill the necessary input fields. You can get the package name from AndroidManifest.xml file which is located in the /android/app/src/main/ folder of the project folder. To get SHA1 key enter the following command in your terminal.

    cd android/ && ./gradlew signingReport
    

    Now after adding the SHA1 key click on create. You will get your new OAuth client ID.

    Now time to code

  18. Create a simple screen with two Date and Time picker (One for event start time and one for event end time) and an input field for entering the event name.

    main.dart

    import 'package:flutter/material.dart';
    import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const AddEvent(),
        );
      }
    }
    
    class AddEvent extends StatefulWidget {
      const AddEvent({super.key});
    
      @override
      State<AddEvent> createState() => _AddEventState();
    }
    
    class _AddEventState extends State<AddEvent> {
      DateTime startTime = DateTime.now();
      DateTime endTime = DateTime.now().add(const Duration(days: 1));
      final TextEditingController _eventName = TextEditingController();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: SizedBox(
                width: double.infinity,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(
                      height: 40,
                    ),
                    const Text(
                      "Add Event to google Calender",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    const Text(
                      "Choose Date and Time",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: Colors.black54,
                      ),
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    Row(
                      children: <Widget>[
                        TextButton(
                            onPressed: () {
                              DatePicker.showDateTimePicker(context,
                                  showTitleActions: true,
                                  minTime: DateTime(2019, 3, 5),
                                  maxTime: DateTime(2200, 6, 7),
                                  onChanged: (date) {}, onConfirm: (date) {
                                setState(() {
                                  startTime = date;
                                });
                              },
                                  currentTime: DateTime.now(),
                                  locale: LocaleType.en);
                            },
                            child: const Text(
                              'Event Start Time',
                              style: TextStyle(color: Colors.blue),
                            )),
                        Text('$startTime'),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        TextButton(
                            onPressed: () {
                              DatePicker.showDateTimePicker(context,
                                  showTitleActions: true,
                                  minTime: DateTime(2019, 3, 5),
                                  maxTime: DateTime(2200, 6, 7),
                                  onChanged: (date) {}, onConfirm: (date) {
                                setState(() {
                                  endTime = date;
                                });
                              },
                                  currentTime: DateTime.now(),
                                  locale: LocaleType.en);
                            },
                            child: const Text(
                              'Event End Time',
                              style: TextStyle(color: Colors.blue),
                            )),
                        Text('$endTime'),
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: TextField(
                        controller: _eventName,
                        decoration: const InputDecoration(
                            hintText: 'Enter Event name',
                            border: OutlineInputBorder()),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: SizedBox(
                        height: 40,
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () {},
                          child: const Text("Add"),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    

    Home Screen will look like this

    alt

  19. Add to calender function

    calender_client.dart

    Add required Packages

    googleapis -> for using google calender api

    googleapis_auth -> for creating OAuth access Token

    extension_google_sign_in_as_googleapis_auth -> for creating AuthClient instances for google calender API

  20. Import the packages

    import 'package:googleapis/calendar/v3.dart';
    import 'package:google_sign_in/google_sign_in.dart';
    import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
    
  21. Now SignIn into google under the scope of google calender api

    final googleSignIn = GoogleSignIn(
      scopes: <String>[CalendarApi.calendarScope],
    );
    await googleSignIn.signIn();
    

    Here we are using calenderScope (https://www.googleapis.com/auth/calendar) to add event into google calender

  22. After signin create an AuthClient instance which will hold the OAuth access tokens and pass it to the calender api

    final client = await googleSignIn.authenticatedClient();
    CalendarApi calendar = CalendarApi(client);
    
  23. Now create an event to add into the calender

    final DateTime startDate;
    final DateTime endDate;
    final String eventName;
    
    Event event = Event(
      start: EventDateTime(date: startDate),
      end: EventDateTime(date: endDate),
      summary: eventName,
    );
    
  24. Now finally insert the event into calender

    if (client != null) {
      CalendarApi calendar = CalendarApi(client);
      String calendarId = "primary";
      try {
        await calendar.events.insert(event, calendarId);
        debugPrint("Added to Calender");
      } catch (e) {
        debugPrint("Failed to add");
      }
    }
    

    The whole calender_client.dart will look like this

    import 'package:flutter/material.dart';
    import 'package:googleapis/calendar/v3.dart';
    import 'package:google_sign_in/google_sign_in.dart';
    import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
    
    class CalenderClient {
      final DateTime startDate;
      final DateTime endDate;
      final String eventName;
      CalenderClient(this.startDate, this.endDate, this.eventName);
    
      Future<void> addToCalender(DateTime start, DateTime end, String name) async {
        Event event = Event(
          start: EventDateTime(date: start),
          end: EventDateTime(date: end),
          summary: name,
        );
        final googleSignIn = GoogleSignIn(
          scopes: <String>[CalendarApi.calendarScope],
        );
        await googleSignIn.signIn();
        final client = await googleSignIn.authenticatedClient();
        if (client != null) {
          CalendarApi calendar = CalendarApi(client);
          String calendarId = "primary";
          try {
            await calendar.events.insert(event, calendarId);
            debugPrint("Added to Calender");
          } catch (e) {
            debugPrint("Failed to add");
          }
        }
      }
    }
    
  25. Now finally wire the addToCalender function into the Add button in home page

    ElevatedButton(
        onPressed: () {
            CalenderClient client = CalenderClient(startTime, endTime, eventName.text);
            client.addToCalender(startTime, endTime, eventName.text);
        },
        child: const Text("Add"),
    ),
    

    Final Result

    alt

Done

You can find the github repo here