Flutter社交登录插件social_sign_in的使用
Flutter社交登录插件social_sign_in的使用
social_sign_in
是一个帮助你在应用中使用Facebook、Google、Microsoft和Apple进行社交登录的Flutter插件。它利用Firebase来实现这些功能。
开始使用
首先,在你的项目中添加social_sign_in
依赖。
dependencies:
social_sign_in: ^0.0.6
Firebase设置
为了配置Firebase,你需要按照以下步骤操作:
- 使用Google账户登录到Firebase控制台。
- 创建一个新的Firebase项目。
- 在项目中点击身份验证,启用该功能。
- 在Meta开发者网站、Google控制台、Microsoft Azure和Apple开发者网站上分别创建相应的应用。
- 导航到登录方法标签页,启用你想要支持的登录提供商。
- 除了Google登录外,你需要在所支持的社交提供商的控制台网站上配置重定向URL(即当你启用特定社交提供商时生成的URL)。
使用Facebook进行登录
- 在Meta开发者网站启动应用程序创建过程。
- 选择一个使用场景,确定应用可用的权限、产品和API。
- 设置应用名称和邮箱。
- 指定你刚刚创建的应用的Client ID和Client Secret。
使用Google进行登录
- 在Google控制台创建授权凭据。
- 指定你刚刚创建的应用的Client ID和Client Secret。
使用Microsoft进行登录
- 登录Azure门户,点击Azure Active Directory,然后在导航面板中点击应用注册以注册一个应用。
- 输入你的应用名称,并选择**任何组织目录中的帐户和个人Microsoft帐户(例如Skype、Xbox)**以允许从组织和个人帐户登录。
- 选择Web作为重定向URI,并在Firebase控制台下的身份验证 > 登录方法 > 启用Microsoft提供商中输入重定向URI。
- 在证书和密钥中添加新的客户端密钥。
- 指定你刚刚创建的应用的Client ID和Client Secret。
使用Apple进行登录
- 在Xcode中构建应用时,它会自动在Apple开发者网站上创建一个应用。如果未自动创建,请手动创建,设置描述和Bundle ID。
- 添加使用Apple登录功能并在Xcode中重启应用。(Runner (文件浏览器侧边栏) -> 目标 -> Runner -> 签名与能力)
- 在Apple开发者网站上服务ID中创建一个服务ID并启用使用Apple登录功能(稍后配置)。
- 在Apple开发者网站上创建一个密钥并启用使用Apple登录服务。
- 导航到Firebase控制台中的登录方法标签页,启用Apple提供商作为登录提供商。
- 输入服务ID(步骤3中创建的)、团队ID、密钥ID和私钥(步骤4中下载的密钥,扩展名为.p8)。
- 为了在Android和Windows设备上使用Apple登录,需要额外配置。
Android
- 在Firebase云函数中部署一个API来获取重定向URL。
- 在Apple开发者网站上设置服务ID的重定向URL和域。
- 修改android/app/src/main/AndroidManifest.xml文件。
- 部署一个带有Apple登录功能的网页。
Windows
- 在Firebase云函数中部署一个API来获取重定向URL。
- 在Firebase托管中部署一个页面以获取主机页面URL。
- 在Apple开发者网站上设置服务ID的重定向URL、重定向域和主机页面域。
使用
导入social_sign_in.dart
库。
import 'package:social_sign_in/social_sign_in.dart';
登录
调用以下示例中的方法。更多详细信息请参阅example
文件夹和源代码。
// 单步配置和触发登录
SocialSignIn().initialSite(
FacebookSignInConfig(
clientId: [YOUR_FACEBOOK_CLIENT_ID],
clientSecret: [YOUR_FACEBOOK_CLIENT_SECRET],
redirectUrl: [YOUR_LOGIN_REDIRECT_URL],
),
null
);
OutlineButton(
onPressed: () async {
final authResult = await SocialSignIn().signInSite(SocialPlatform.facebook, context);
printSignInResult(authResult);
},
child: const Text('登录Facebook'),
),
// 分步配置和触发登录
OutlineButton(
onPressed: () async {
SocialSignIn()
.initialSite(
GoogleSignInConfig(
clientId: [YOUR_GOOGLE_CLIENT_ID],
clientSecret: [YOUR_GOOGLE_CLIENT_SECRET],
redirectUrl: [YOUR_LOGIN_REDIRECT_URL],
),
null
)
.signIn(context)
.then((authResult) => {
// 处理登录结果
});
},
child: const Text('登录Google')
),
完整示例
以下是一个完整的示例,展示了如何配置和触发登录。
import 'package:flutter/material.dart';
import 'package:sign_in_button/sign_in_button.dart';
import 'package:social_sign_in/social_sign_in.dart';
import 'package:social_sign_in_example/private_data.dart';
void main() {
try {
SocialSignIn().initialSite(
AppleSignInConfig(
clientId: SocialPrivateData.appleServiceId,
redirectUrl: SocialPrivateData.appleRedirectUrl,
hostUrl: SocialPrivateData.appleHostUrl,
),
null);
SocialSignIn().initialSite(
FacebookSignInConfig(
clientId: SocialPrivateData.facebookClientId,
clientSecret: SocialPrivateData.facebookClientSecret,
redirectUrl: SocialPrivateData.simpleRedirectUrl,
),
null);
SocialSignIn().initialSite(
GoogleSignInConfig(
clientId: SocialPrivateData.googleClientId,
clientSecret: SocialPrivateData.googleClientSecret,
redirectUrl: SocialPrivateData.simpleRedirectUrl,
),
null);
SocialSignIn().initialSite(
MicrosoftSignInConfig(
clientId: SocialPrivateData.microsoftClientId,
clientSecret: SocialPrivateData.microsoftClientSecret,
redirectUrl: SocialPrivateData.simpleRedirectUrl,
),
null);
} catch (e) {
debugPrint("initial exception ${e.toString()}");
}
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
home: LoginPage(),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
[@override](/user/override)
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
String _result = "None";
String _detail = "";
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
printSignInResult(SocialSignInResultInterface result) {
if (result.status != SignInResultStatus.ok) {
setState(() {
_detail = result.errorMessage;
_result = result.status == SignInResultStatus.cancelled
? "Cancelled"
: "Failed";
});
} else {
String tmp = "${result.accessToken} ${result.idToken}";
if (tmp.length > 20) {
tmp = "${tmp.substring(0, 17)}...";
}
setState(() {
_detail = "Access Token: $tmp";
_result = "Success";
});
}
}
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: _result == "Success" ? Colors.green : Colors.yellow,
child: Text("Social sign-in: $_result"),
),
Text(_detail),
SignInButton(
Buttons.apple,
onPressed: () async {
final authResult = await SocialSignIn()
.signInSite(SocialPlatform.apple, context);
printSignInResult(authResult);
},
),
SignInButton(
Buttons.google,
onPressed: () async {
// final authResult = await SocialSignIn().signInSite(SocialPlatform.google, context);
SocialSignIn()
.initialSite(
GoogleSignInConfig(
clientId: SocialPrivateData.googleClientId,
clientSecret: SocialPrivateData.googleClientSecret,
redirectUrl: SocialPrivateData.simpleRedirectUrl,
),
null)
.signIn(context)
.then((value) => {printSignInResult(value)});
},
),
SignInButton(
Buttons.facebook,
onPressed: () async {
// Trigger the sign-in flow
final authResult = await SocialSignIn()
.signInSite(SocialPlatform.facebook, context);
printSignInResult(authResult);
},
),
SignInButton(
Buttons.microsoft,
onPressed: () async {
// Trigger the sign-in flow
final authResult = await SocialSignIn()
.signInSite(SocialPlatform.microsoft, context);
printSignInResult(authResult);
},
),
],
),
));
}
}
更多关于Flutter社交登录插件social_sign_in的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter社交登录插件social_sign_in的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用social_sign_in
插件来实现社交登录的示例代码。这个示例将展示如何使用Google登录作为社交登录的一个例子。请注意,实际项目中你可能需要根据具体需求调整代码,并处理错误、用户数据获取等额外逻辑。
首先,确保你已经在pubspec.yaml
文件中添加了social_sign_in
依赖:
dependencies:
flutter:
sdk: flutter
social_sign_in: ^x.y.z # 替换为最新版本号
然后运行flutter pub get
来安装依赖。
接下来,配置Google登录。你需要在Google Cloud Console中创建一个OAuth 2.0客户端ID,并获取相关的客户端ID和客户端密钥。将这些信息添加到你的android/app/src/main/AndroidManifest.xml
和iOS的配置文件中(如果需要iOS支持的话)。
以下是一个简化的Flutter应用示例,展示了如何使用social_sign_in
插件进行Google登录:
import 'package:flutter/material.dart';
import 'package:social_sign_in/social_sign_in.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Social Sign In Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SocialSignInDemo(),
);
}
}
class SocialSignInDemo extends StatefulWidget {
@override
_SocialSignInDemoState createState() => _SocialSignInDemoState();
}
class _SocialSignInDemoState extends State<SocialSignInDemo> {
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/userinfo.profile',
],
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Social Sign In Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
// 在这里你可以使用googleAuth.accessToken来获取用户信息或进行其他操作
print('Google Access Token: ${googleAuth.accessToken}');
print('Google ID Token: ${googleAuth.idToken}');
print('Google User Email: ${googleUser.email}');
print('Google User Name: ${googleUser.displayName}');
// 显示登录成功信息或导航到其他页面
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('登录成功: ${googleUser.displayName}')),
);
}
} catch (e) {
print('Google Sign In failed: $e');
// 显示错误信息
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('登录失败: $e')),
);
}
},
child: Text('使用Google登录'),
),
),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮,用户点击该按钮后,将触发Google登录流程。登录成功后,将打印出Google的访问令牌、ID令牌、用户的电子邮件和显示名称。
请注意,为了在实际应用中使用此代码,你需要确保:
- 已经在Google Cloud Console中正确配置了OAuth 2.0客户端ID,并将相关的客户端ID和密钥配置到你的应用中。
- 添加了必要的权限和配置到Android和iOS项目中,以便应用能够访问Google登录服务。
此外,如果你计划支持其他社交登录(如Facebook、Twitter等),你需要查看social_sign_in
插件的文档,了解如何配置和使用相应的登录服务。