如何在Flutter中获取Google登录访问令牌

时间:2020-04-16 16:11:07

标签: flutter

我想从Google登录中获取访问令牌。我已经做过Google登录编码,但是我只获得displayName,email,id和photoUrl。我可以知道如何获取访问令牌吗?

这是我的代码:

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

class SignInDemo extends StatefulWidget {
  @override
  State createState() => SignInDemoState();
}

class SignInDemoState extends State<SignInDemo> {
  GoogleSignInAccount _currentUser;
  String _contactText;

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
      setState(() {
        _currentUser = account;
      });
    });
  }


  Future<void> _handleSignIn() async {
    try {
      var user = await _googleSignIn.signIn();
      print(user);
    } catch (error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() => _googleSignIn.disconnect();
}

2 个答案:

答案 0 :(得分:3)

您可以使用GoogleSignInAuthentication类来获取访问令牌;

Future<void> _handleSignIn() async {
  try {
    GoogleSignInAccount user = await _googleSignIn.signIn();

    GoogleSignInAuthentication googleSignInAuthentication = await user.authentication;

    print(googleSignInAuthentication.accessToken);


  } catch (error) {
    print(error);
  }
}

答案 1 :(得分:1)

你可以试试这个

_googleSignIn.signIn().then((result){
          result.authentication.then((googleKey){
              print(googleKey.accessToken);
              print(googleKey.idToken);
          }).catchError((err){
            print('Error occured inside');
          });
      }).catchError((err){
          print('Error occured outside');
      });

享受编码!

相关问题