How to use Google API in flutter?
I can't add comments yet, so I'll just post it as an answer.
I kept trying to make a GoogleHttpClient as per the top answer, but on the import, it says "The library 'package:http/http.dart' doesn't export a member with the shown name 'IOClient'."
I found the answer here https://pub.dartlang.org/packages/http#-changelog-tab-, which says you should import IOClient separately as such: import 'package:http/io_client.dart';
I thought this might help out others who are new to flutter and its implementation of Google APIs.
This worked for me:
Logging in using package google_sign_in
and then get auth headers from it:
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;
// custom IOClient from below
final httpClient = GoogleHttpClient(authHeaders);
data = await PeopleApi(httpClient).people.connections.list(
'people/me',
personFields: 'names,addresses',
pageToken: nextPageToken,
pageSize: 100,
);
}
This is a custom IOClient
implementation that automatically adds the auth headers to each request. The googleapis call support passing a custom HTTP client to be used instead of the default (see above)
import 'package:http/io_client.dart';
import 'package:http/http.dart';
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));
}