Cara Menggunakan Google API di Flutter

Tutorial dan snippet kecil bagi yang penasaran bagaimana cara menggunakan Google API di aplikasi yang ditulis menggunakan Flutter SDK. Secara resmi, sudah ada library khusus yang menjawab kasus khusus ini.

Silakan ikut satu dari snippet code berikut:

1. Bikin Class dan Alur sendiri dari Google Sign In

Pertama, gunakan library Google Sign In di Dart:

import 'package:google_sign_in/google_sign_in.dart'
    show GoogleSignIn, GoogleSignInAccount;

import 'package:googleapis/people/v1.dart'
    show ListConnectionsResponse, PeopleApi;

useGoogleApi() async {
  final _googleSignIn = new GoogleSignIn(
    scopes: [
      'email',
      'https://www.googleapis.com/auth/contacts.readonly',
    ],
  );

  await _googleSignIn.signIn();

  final authHeaders = _googleSignIn.currentUser.authHeaders;
  final httpClient = new GoogleHttpClient(authHeaders);

  data = await new PeopleApi(httpClient).people.connections.list(
      'people/me',
      personFields: 'names,addresses',
      pageToken: nextPageToken,
      pageSize: 100,
  );
}

Kemudian, untuk class GoogleHttpClient() bisa contoh source code berikut:

import 'package:http/http.dart'
    show BaseRequest, IOClient, Response, StreamedResponse;

class GoogleHttpClient extends IOClient {
  Map<String, String> _headers;

  GoogleHttpClient(this._headers) : super();

  @override
  Future<StreamedResponse> send(BaseRequest request) =>
      super.send(request..headers.addAll(_headers));

  @override
  Future<Response> head(Object url, {Map<String, String> headers}) =>
      super.head(url, headers: headers..addAll(_headers));

}

2. Menggunakan Class Google APIs Resmi

Silakan menggunakan Google APIs dari tim pengembang Dart disini: https://pub.dartlang.org/packages/googleapis.

Tambahkan dependency Google API di pubspec flutter-mu:

dependencies:
  googleapis: any
  googleapis_auth: any

kemudian implementasikan, contohnya:

import 'package:googleapis/storage/v1.dart';
import 'package:googleapis_auth/auth_io.dart';

final _credentials = new ServiceAccountCredentials.fromJson(r'''
{
  "private_key_id": ...,
  "private_key": ...,
  "client_email": ...,
  "client_id": ...,
  "type": "service_account"
}
''');

const _SCOPES = const [StorageApi.DevstorageReadOnlyScope];

void main() {
  clientViaServiceAccount(_credentials, _SCOPES).then((http_client) {
    var storage = new StorageApi(http_client);
    storage.buckets.list('dart-on-cloud').then((buckets) {
      print("Received ${buckets.items.length} bucket names:");
      for (var file in buckets.items) {
        print(file.name);
      }
    });
  });
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: