Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

dart - 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 theGoogle API_AUTH dependence is working for 0.2.1. How do I implement them ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...