How to api call of google calendar in flutter공부방/Flutter2024. 5. 31. 18:08
Table of Contents
기록용으로 메모해 두어요.
먼저 Firebase google login 이 구현이 되어있다고 가정하고, 진행 할게요.
만약 Firebase google login이 설정이 되어있지 않다면, 다른 분들의 글에서 참고해서 셋팅해주세요.
1. google api 라이브러리 설치
pubspec.yaml
googleapis: ^13.1.0
2. 전체 코드
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:signal/core/core.dart';
import 'package:googleapis/calendar/v3.dart' as calendar;
import 'package:http/http.dart' as http;
class GoogleCalendarTest {
Future<void> callCalendarAPI() async {
///scopes에 요청할 권한을 미리 정의해 주어야 해요!!!!
final GoogleSignIn googleSignIn = GoogleSignIn(
scopes: [
calendar.CalendarApi.calendarScope,
calendar.CalendarApi.calendarReadonlyScope,
],
);
final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
if (googleUser == null) {
Logger.log('Google Sign In Fail');
return;
}
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
http.Client client = http.Client();
final authHeaders = {
'Authorization': 'Bearer ${credential.accessToken}',
};
final baseClient = AuthenticatedClient(client, authHeaders);
final calendarApi = calendar.CalendarApi(baseClient);
final calendarListResource = calendarApi.calendarList;
final calendarList = await calendarListResource.list();
calendarList.items?.forEach((element) {
Logger.log('Calendar Id: ${element.id}');
});
final events = await calendarApi.events.list(calendarList.items?.firstOrNull?.id ?? 'primary');
events.items?.forEach((element) {
Logger.log('element.summary: ${element.summary}, date: ${element.start?.dateTime}');
});
return Future.value();
}
}
class AuthenticatedClient extends http.BaseClient {
final http.Client _inner;
final Map<String, String> _headers;
AuthenticatedClient(this._inner, this._headers);
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _inner.send(request..headers.addAll(_headers));
}
}
3. 실행
///테스트 코드
void run() async {
GoogleCalendarTest().callCalendarAPI();
}
반응형
'공부방 > Flutter' 카테고리의 다른 글
@soycrab :: 꿀맛코딩
행복한 코딩을 위하여!
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!