Flutter谷歌认证插件google_auth的使用
Flutter谷歌认证插件google_auth的使用
配置
Android
无需配置。
iOS
官方文档:https://developers.google.com/identity/sign-in/ios/start-integrating
在info.plist
文件中添加以下内容:
<key>GIDClientID</key>
<string>$(DEFINE_GOOGLE_CLIENT_ID_IOS)</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>$(DEFINE_GOOGLE_URL_SCHEME_IOS)</string>
</array>
</dict>
</array>
其中$(DEFINE_GOOGLE_CLIENT_ID_IOS)
和$(DEFINE_GOOGLE_URL_SCHEME_IOS)
分别是你的应用的客户端ID(iOS)和iOS URL Scheme。
使用
-
在
pubspec.yaml
中添加插件:dependencies: google_auth: ^版本号
然后运行
flutter pub get
。 -
在Dart代码中导入插件:
import 'package:google_auth/google_auth.dart';
-
认证用户:
GoogleAuth().signIn(clientId);
其中
clientId
为:- 对于Android,客户端ID应设置为Web应用的ID。注意:如果使用Android应用的客户端ID,会收到一个错误,提示开发者控制台未正确设置。
- 对于iOS,此参数被忽略,可以传递任意字符串。
该函数返回一个Future
对象,解析为以下格式的对象:
-
iOS:
{ "idToken"?: String "idTokenExpire"?: int "accessToken": String "accessTokenExpire"?: int "userID"?: String "refreshToken": String "refreshTokenExpire"?: int "email"?: String "name"?: String "givenName"?: String "familyName"?: String "image"?: String }
-
Android:
{ "idToken": String }
-
登出用户:
GoogleAuth().signOut(): Future<void>
-
处理可能的错误码:
try { return {'idToken': await GoogleAuth().signIn(clientId)}; } on PlatformException catch (e) { if (e.code == 'API_CANCELED' || e.code == 'GSI_SIGN_IN_CANCELLED') { throw AppError('User has cancelled'); } rethrow; }
SDK版本
-
Android:
implementation 'com.google.android.gms:play-services-auth:20.5.0'
-
iOS:
s.dependency 'GoogleSignIn', '~> 7.0'
示例代码
以下是一个完整的示例代码,展示了如何使用google_auth
插件进行谷歌认证:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:google_auth/google_auth.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _googleAuthPlugin = GoogleAuth();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
// 平台消息异步处理,初始化状态
Future<void> initPlatformState() async {
String platformVersion;
// 平台消息可能会失败,因此我们使用带有PlatformException的try/catch块
// 我们还处理消息可能返回null的情况
try {
platformVersion =
await _googleAuthPlugin.getPlatformVersion() ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// 如果小部件在异步平台消息处理期间从树中移除,则丢弃回复而不是调用setState来更新我们的非存在的外观
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running on: $_platformVersion\n'),
),
),
);
}
}
更多关于Flutter谷歌认证插件google_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter谷歌认证插件google_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用google_auth
插件来实现谷歌认证的代码示例。请注意,这个插件可能不是官方维护的,Flutter社区中更常用的插件是google_sign_in
。不过,为了回答你的问题,我会假设google_auth
插件的API与google_sign_in
类似,并提供一个基于google_sign_in
的示例代码,因为google_auth
的具体实现细节可能有所不同,但流程应该是类似的。
首先,确保在你的pubspec.yaml
文件中添加了依赖项:
dependencies:
flutter:
sdk: flutter
google_sign_in: ^5.0.0 # 假设使用google_sign_in作为示例
然后运行flutter pub get
来安装依赖。
接下来,配置你的Android和iOS项目以支持Google Sign-In。
Android配置
- 在
android/app/src/main/AndroidManifest.xml
中添加必要的权限和元数据:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<application
... >
<!-- Add the following line -->
<meta-data
android:name="com.google.android.gms.auth.api.signin.enabled"
android:value="true" />
</application>
<!-- Add the following permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
</manifest>
- 在
android/app/build.gradle
中配置Google服务插件:
dependencies {
// Add the following line
implementation 'com.google.android.gms:play-services-auth:19.0.0'
}
iOS配置
- 在
ios/Runner/Info.plist
中添加以下条目:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>YOUR_REVERSED_CLIENT_ID</string>
</array>
</dict>
</array>
<key>GoogleService-Info.plist</key>
<string>Resources/GoogleService-Info.plist</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechrome</string>
<string>comgooglemaps</string>
</array>
- 下载并添加
GoogleService-Info.plist
到你的ios/Runner
目录中。
Flutter代码实现
现在,你可以在Flutter代码中使用Google Sign-In了。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SignInScreen(),
);
}
}
class SignInScreen extends StatefulWidget {
@override
_SignInScreenState createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/userinfo.profile',
],
);
Future<void> _handleSignIn() async {
try {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
if (googleUser == null) return;
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
// Create a new credential using GoogleAuthProvider.credential
// This is typically used with Firebase Authentication
// final credential = GoogleAuthProvider.credential(
// idToken: googleAuth.idToken,
// accessToken: googleAuth.accessToken,
// );
// You can now use the `credential` object to authenticate with Firebase
// For demonstration purposes, let's just print the user's info
print('''
User ID: ${googleUser.id}
Email: ${googleUser.email}
Display Name: ${googleUser.displayName}
Photo URL: ${googleUser.photoUrl}
''');
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Sign-In'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
ElevatedButton(
onPressed: _handleSignIn,
child: Text('Sign in with Google'),
),
],
),
),
);
}
}
这个示例展示了如何使用google_sign_in
插件进行谷歌认证。如果你确实在使用google_auth
插件,并且它的API与google_sign_in
不同,请参考该插件的官方文档进行配置和使用。由于google_auth
不是Flutter官方或广泛使用的插件,因此提供的帮助可能有限,但上述流程应该为你在Flutter中实现谷歌认证提供了一个良好的起点。