简体   繁体   中英

How to use Google API in flutter?

I want to use Google Cloud Natural Language in my Flutter app,I got Google API package This works for flutter and the Google API_AUTH dependence is working for 0.2.1. How do I implement them?

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));

}

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.

The accepted answer is most likely written towards an older version of the SDK I just couldn't get it to work. This is what works for me as of now.

As an example, the following allow us to access files in Google Drive which is part of googleapis .

Dependencies

pubspec.yaml:

dependencies:
  google_sign_in: any
  googleapis: any

(I just put any here as a example, but you should specific the version(s) for you actual app.)

How it works

Necessary imports:

import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart' as signIn;

Step 1, sign in the user and ask for access permission (scope) to google drive:

final googleSignIn = signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.DriveScope]);
final sign.GoogleSignInAccount account = await googleSignIn.signIn();

Step 2, build a AuthenticateClient :

class AuthenticateClient extends http.BaseClient {
  final Map<String, String> headers;

  final http.Client client;

  AuthenticateClient(this.headers, this.client);

  Future<http.StreamedResponse> send(http.BaseRequest request) {
    return client.send(request..headers.addAll(headers));
  }
}

As suggested in http , this is using the BaseClient with extra authentication headers (being composable).

Step 3, create a authenticated http client with from step 1 and 2 and access google drive API.

final baseClient = new Client();
final authenticateClient = AuthenticateClient(authHeader, baseClient);
final driveApi = drive.DriveApi(authenticateClient);

Checkout How to Use the Google Drive API With Flutter Apps for details.

Update to the accepted answer

Along with google_sign_in and googleapis packages, now you can use extension_google_sign_in_as_googleapis_auth package (provided by flutter.dev) to get configured http client. So the accepted answer can be simplified to below. No implementation of GoogleHttpClient is necessary.

import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/people/v1.dart';

useGoogleApi() async {
  final _googleSignIn = new GoogleSignIn(
    scopes: [
      'email',
      PeopleServiceApi.contactsReadonlyScope,
    ],
  );

  await _googleSignIn.signIn();

  // custom IOClient
  final httpClient = await _googleSignIn.authenticatedClient();

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

You need to get 2 packages googleapis_auth and googleapis after you can use all listed apis in googleapis packages. I will show you under an example

import 'package:googleapis/androidpublisher/v3.dart' as androidPublisher;
import 'package:googleapis_auth/auth_io.dart' as auth;

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

    const _SCOPES = const [
      androidPublisher.AndroidpublisherApi.AndroidpublisherScope
    ];

    auth.clientViaServiceAccount(_credentials, _SCOPES).then((httpClient) {
      var publisher = new androidPublisher.AndroidpublisherApi(httpClient);
      publisher.purchases.products
          .get(
              packageName,
              productID,
              purchaseToken)
          .then((pub) {
        debugPrint(pub.toJson().toString());
      });
    });

And you can creat keys like that

Open the IAM & Admin page in the Cloud Console.

Open the IAM & Admin page

Click Select a project, choose a project, and click Open.

In the left nav, click Service accounts.

Find the row of the service account that you want to create a key for. In that row, click the More more_vert button, and then click Create key.

Select a Key type and click Create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM