首页 > 解决方案 > 如何通过谷歌登录获取访问令牌——Flutter

问题描述

我想从 google sign 获取访问令牌并将其保存为变量,这样我就可以将它推送到我自己的 API,这个问题之前已经被问过,但答案已经过时了。我正在使用这个包:谷歌登录 她,我通过按钮访问的登录代码:

  GestureDetector(
                              onTap: () {
                                _googleSignIn.signIn().catchError((e) {
                                  print('Erorr');
                                });
                                ;
                              },

标签: flutterflutter-layoutflutter-dependencies

解决方案


使用谷歌登录时获取访问令牌

final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth?.accessToken,
    idToken: googleAuth?.idToken,
  );

完整方法:

import 'package:google_sign_in/google_sign_in.dart';

Future<UserCredential> signInWithGoogle() async {
  // Trigger the authentication flow
  final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

  // Obtain the auth details from the request
  final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;

  // Create a new credential
  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth?.accessToken,
    idToken: googleAuth?.idToken,
  );

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

对于文档https://firebase.flutter.dev/docs/auth/social/


推荐阅读