📅  最后修改于: 2023-12-03 15:15:24.790000             🧑  作者: Mango
Google Sign In 是一种用于在 Flutter 应用程序中进行身份验证的方法。当用户使用他们的 Google 帐户登录应用程序时,应用程序会收到一个 OAuth2 访问令牌,该令牌可以用于访问用户帐户的受保护数据。本文将为您介绍如何使用 Google Sign In 来获取访问令牌,以及如何将其用于访问 Google API。
在 Flutter 中使用 Google Sign In 需要进行一些设置,包括在您的 Google Cloud Console 中创建 OAuth2 客户端密钥和配置 Flutter 应用程序以与您的 Google 帐户进行身份验证。
dependencies:
google_sign_in: ^4.5.1
import 'package:google_sign_in/google_sign_in.dart';
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
Future<void> _handleSignIn(BuildContext context) async {
try {
await _googleSignIn.signIn();
// 获取访问令牌并将其用于访问Google API
// ...
} catch (error) {
print(error);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Sign In Example'),
),
body: Center(
child: RaisedButton(
onPressed: () => _handleSignIn(context),
child: Text('Sign in with Google'),
),
),
);
}
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> _handleSignIn(BuildContext context) async {
try {
await _googleSignIn.signIn();
final GoogleSignInAccount googleUser = _googleSignIn.currentUser;
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final String accessToken = googleAuth.accessToken;
// 使用访问令牌访问 Google API
final response = await http.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
headers: {'Authorization': 'Bearer $accessToken'},
);
final userInfo = json.decode(response.body);
print(userInfo);
} catch (error) {
print(error);
}
}
Google Sign In 为 Flutter 开发人员提供了一种简单但强大的身份验证方法,可以轻松地与 Google API 一起使用。通过遵循本文中提供的步骤,在您的 Flutter 应用程序中使用 Google Sign In 来获得访问令牌,并使用它来访问 Google API。