Using Google calender api with flutter
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 :-⌗
-
Go to the Google API Dashboard (https://console.cloud.google.com/apis/dashboard)
-
Sign in with your gmail.
-
You will see an interface like this. Click on My Project
All your projects should be listed here
-
Create a new project
-
Add your project name and create a new project
-
Return to the desktop and open your newly created project from the list.
-
Click on Enable Api and Services from the menu
-
Click on ENABLE API AND SERVICES
-
Search for the Google Calender API and enable it. Now return to the Dashboard.
-
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
-
Now add necessary information and click on continue
-
Now click on Add or Remove scopes and add Google Calender API in the scope and click on update
-
In the next section add test users and click on save and continue. Review your OAuth Consent summary and continue
-
Create a new flutter project using the command
flutter create myapp
-
Now we have to create OAuth Client ID. Go to the credentials section click on Create Credentials.
-
Click on OAuth client ID
-
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
-
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
-
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
-
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';
-
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
-
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);
-
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, );
-
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"); } } } }
-
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⌗
Done⌗
You can find the github repo here