Flutter无法从Google API获取数据

时间:2019-11-01 08:48:12

标签: firebase dart google-api google-signin flutter-dependencies

我正在尝试访问Google People API以获取一些用户数据,例如姓名,电子邮件等。我使用了google_sign_in插件和firebase_auth通过Google登录登录用户,然后我想在那里提到他的数据并将其保存到我的数据库中。问题在于,我尝试过的一切似乎都没有效果,而且我真的找不到更多的信息。同样,您现在必须将google_sign_in与firebase_auth结合使用,并且不能仅在没有Firebase的情况下使用它吗?因为我只需要来自People API的userData。

我在堆栈上发现的某些“解决方案”无法正常工作,其中之一是How to use Google API in flutter? 我也尝试使用此代码https://github.com/flutter/plugins/blob/master/packages/google_sign_in/example/lib/main.dart,但是它没有Firebase,而且我看到人们说您现在必须将它与Firebase一起使用。

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis/people/v1.dart';
import 'package:http/http.dart'
    show BaseRequest, IOClient, Response, StreamedResponse, get;
import 'package:http/io_client.dart';

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

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


final FirebaseAuth _auth = FirebaseAuth.instance;

final GoogleSignIn googleSignIn = GoogleSignIn(
  scopes: <String>['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email'],
);



Future<String> signInWithGoogle() async {

  final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication =
  await googleSignInAccount.authentication;

  final authHeaders = googleSignIn.currentUser.authHeaders;






  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  final AuthResult authResult = await _auth.signInWithCredential(credential);
  final FirebaseUser user = authResult.user;

  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);

  return 'signInWithGoogle succeeded: $user';

}

void signOutGoogle() async{
  await googleSignIn.signOut();

  print("User Sign Out");
}



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

}

除了只显示“使用Google登录”对话框外,我单击了该对话框,然后我从People API中获取了他的数据,并将其发送到我的后端,并根据他的数据创建了一个用户实例。基本上就是:)

1 个答案:

答案 0 :(得分:0)

希望您能解释一些代码:)

这个人here是一个完美的Google登录示例。

Google People Api适用于用户联系人,因此您需要使用thisthis软件包。

  

现在同时需要google_sign_in和firebase_auth吗?

是的,然后通过以下方式将Google登录名与firebase_auth用户链接:

await authInstance.signInWithCredential(credential);
相关问题