一尘不染

如何在Flutter中使用Google API?

flutter

我想在Flutter应用程序中使用Google Cloud Natural Language,我得到了Google
API程序包。
该程序适用于Flutter,并且Google
API_AUTH
依赖关系适用于0.2.1。如何实施?


阅读 454

收藏
2020-08-13

共1个答案

一尘不染

这对我有用:

使用package登录,google_sign_in然后从中获取auth标头:

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

这是一个自定义IOClient实现,可自动将auth标头添加到每个请求。googleapis调用支持传递要使用的自定义HTTP客户端(而非默认值)(请参见上文)

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

}
2020-08-13