Flutter集成Firebase接入Google登录、FackBook登录、Apple登录
官方文档参考链接:
注:由于接入的是Firebase平台,所以所有的请求登录时,手机一定要会科学上网!!不然无法进行登录。
一、pubspec.yaml引入插件
firebase_auth: # 集成三方登录
google_sign_in: # Google登录
flutter_facebook_auth: # FaceBook登录
二、flutter run运行测试能否跑动
小插曲
如果您的项目之前更改过build.gradle中引入库的配置,运行时会出现以下错误
Could not find facebook-common-16.0.1.aar (com.facebook.android:facebook-common:16.0.1).
Searched in the following locations:
https://maven.aliyun.com/repository/jcenter/com/facebook/android/facebook-common/16.0.1/facebook-common-16.0.1.aar
https://maven.aliyun.com/repository/jcenter/com/facebook/android/facebook-common/16.0.1/facebook-common-16.0.1.jar
解决方法
注意flutter_facebook_auth 要求 minSdkVersion的最小使用版本,
android > app > build.gradle
minSdkVersion 21
三、配置Google登录
-
创建
Android应用 -
查看本机的
SHA1与SHA256keytool 实用程序会提示您输入密钥库的密码。调试密钥库的默认密码为androidMac/Linux:keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystoreWindows:keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%.android\debug.keystore -
复制上面输出的
SHA1或者SHA256, 添加到Firebase后台配置上 -
下载并添加配置文件
将下载的 google-services.json 文件移到您的模块(应用级)根目录中。
四、Flutter集成Firebase
-
安装
Firebase CLI参考链接:firebase.google.com/docs/cli?hl…方法一:
curl -sL https://firebase.tools | bash方法二(要求Node为16以上,具体查看报错信息):
npm install -g firebase-tools -
测试运行
firebase login命令会打开与机器上的 localhost 关联的网页。如果您使用的是远程机器且您无权访问 localhost,请运行带有 --no-localhost 标志的命令。 如果授权登录Google账号失败出现:Firebase CLI Login Failed请运行
set "NODE_TLS_REJECT_UNAUTHORIZED=0"set http_proxy=http://127.0.0.1:你的代理端口 -
dart安装并运行
FlutterFire CLIdart pub global activate flutterfire_cli运行完此命令后,会报错警告Warning: Pub installs executables into $HOME/.pub-cache/bin, which is not on your path. You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.): export PATH="$PATH":"$HOME/.pub-cache/bin"我们来修改配置文件,增加变量 运行命令:
vim ~/.bash_profile增加export PATH="$PATH":"$HOME/.pub-cache/bin"wq退出保存vim ~/.zshrc增加export PATH="$PATH":"$HOME/.pub-cache/bin"(末尾最好追加source ~/.bash_profile防止配置不生效)wq退出保存使配置生效
source ~/.zshrcsource ~/.bash_profile -
在 Flutter 项目的根目录下,运行以下命令
flutterfire configure --project=yohomobile-b9ab1出现报错
i Found 0 Firebase projects. Selecting project yohomobile-b9ab1. FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command. COMMAND: firebase projects:list --json ERROR: Failed to authenticate, have you run firebase login?终端运行
firebase login选择,y/n之后,弹出浏览器页面,授权登录账号很长时间后,授权报错:
Firebase CLI Login FailedMac运行命令 设置代理,指定自己的代理端口,10887与10886是我自己的http端口与socks5端口,请换成你的端口export https_proxy=http://127.0.0.1:10887 http_proxy=http://127.0.0.1:10887 all_proxy=socks5://127.0.0.1:10886Windows运行命令set https_proxy=http://127.0.0.1:10887运行
firebase login --no-localhost该命令不会自动打开页面,需要自己复制
打开链接后,首先还是授权登录,接着会询问是不是运行了
firebase login --no-localhost, 会话ID是不是上图中显示的30D0F,紧接着会给你一段code码,将该码复制,粘贴到终端上,即可成功再次运行
flutterfire configure --project=yohomobile-b9ab1出现报错i Found 0 Firebase projects. Selecting project yohomobile-b9ab1. FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command. COMMAND: firebase projects:list --json ERROR: Failed to list Firebase projects. See firebase-debug.log for more info.查看报错日志
firebase-debug.log发现是没有正确登录导致,怀疑是上面增加--no-localhost导致,按照报错信息运行命令重新登录:firebase login --reauth如果您之前关过终端,需要重新运行配置http代理的那一行命令
重新授权登录即可
再次运行命令
flutterfire configure --project=yohomobile-b9ab1这会自动向 Firebase 注册您的每个平台应用,并向您的 Flutter 项目添加
lib/firebase_options.dart配置文件。会询问你生成什么端的,我暂时选择的
Android生成运行成功后,可以看到
lib当中多了个firebase_options.dart文件 -
初始化并运行项目
首先让你的手机能访问科学上网
打开 main.dart
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
......
void main() async {
// 初始化firebase
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
......
调用google登录
// Google登录
Future<UserCredential> signInWithGoogle() async {
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);
}
登录成功后,可通过Firebase提供的方法,拿到token,这个token是用来给后端做校验用的
// 确保用户已经登录,并获取当前用户的身份验证令牌
final currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null) {
final tokenResult = await currentUser.getIdToken();
final token = tokenResult;
print('-----token-----');
// 这里处理您需要使用这个令牌的逻辑,例如将它存储到本地存储中作为凭据。
print(token);
} else {
print('用户未登录');
}
五、配置FaceBook登录
facebook.meedu.app/docs/5.x.x/…
- 配置
Android配置
设置 android/app/build.gradle
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 33
...
}
创建并配置/android/app/src/main/res/values/strings.xml
app_id与client_token都是在facebook应用平台添加配置的
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="facebook_app_id">{your-app-id}</string>
<string name="facebook_client_token">YOUR_CLIENT_TOKEN</string>
</resources>
在/android/app/src/main/AndroidManifest.xml中增加
<uses-permission android:name="android.permission.INTERNET"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
- 配置
IOS配置info.plistyour-app-name是登录的时候显示的名称,不重要
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{your-app-id}</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookClientToken</key>
<string>CLIENT-TOKEN</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>
<key>LSApplicationQueriesSchemes</key>
3. 平台配置Android与IOS 将包名称与平台关联
developers.facebook.com/docs/facebo…
developers.facebook.com/docs/facebo…
`android` 需要注意的是,添加包名需要先在`google play`上架才可以绑定包名
![\[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0oPOxNPP-1690343092847)(media/16873168375462/16879495915893.jpg)\]](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f0dd4f8caba44d1facb6a20d63b2db94~tplv-k3u1fbpfcp-zoom-1.image)
![\[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dAi83Z9N-1690343092847)(media/16873168375462/16879496851366.jpg)\]](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/48c89fa2332e42faba0771fdea71f3c1~tplv-k3u1fbpfcp-zoom-1.image)
ios
- 接下来就可以通过
firebase的方法调用facebook的登录了,通过之后,后面的步骤就和google登录一样,获取token拿给后端使用
// FaceBook登录
Future<UserCredential> signInWithFacebook() async {
// Trigger the sign-in flow
final LoginResult loginResult = await FacebookAuth.instance.login();
EasyLoading.dismiss();
// Create a credential from the access token
final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(loginResult.accessToken!.token);
// Once signed in, return the UserCredential
return FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
}
六、配置IOS登录
注意调用登录的时候不要使用开发者账号,否则拿不到用户信息!!
1. 创建标识符
将您的网站关联至您的应用。出现提示时,将以下网址注册为返回网址:
https://YOUR_FIREBASE_PROJECT_ID.firebaseapp.com/__/auth/handler
YOUR_FIREBASE_PROJECT_ID为你的在firebase平台创建的项目ID
Continue => Register 注册
2.创建Key
选择刚才创建的标识符,Save
根据提示,可以选择是否下载密钥,如果现在下载了,要保存好!!!!! 只有一次下载机会!!!!!
3. 启用 Apple 作为登录提供方
将 Firebase 添加到您的 Apple 项目。当您在 Firebase 控制台中设置应用时,请务必注册应用的软件包 ID。
前提条件:
- Xcode 14.1 或更高版本
- iOS 11
-
在 Firebase 中注册您的应用, 首先添加一个IOS应用
-
下载并安装配置文件
-
添加SDK
右上角搜索 https://github.com/firebase/firebase-ios-sdk
选择安装
Pods与Runner的区别
Xcode是苹果公司开发的集成开发环境(IDE),用于开发macOS、iOS和iPadOS等操作系统的应用程序。在Xcode项目中,添加包通常可以通过CocoaPods或者Flutter的包管理工具来实现。在使用Flutter开发时,添加包可以选择使用CocoaPods或者Flutter的包管理工具runner,它们的区别如下:
- CocoaPods是一个用于管理iOS和macOS项目中第三方库依赖关系的工具,可以将开发所需的包集成到项目中并自动解决依赖问题。使用CocoaPods需要在终端中安装它并创建Podfile文件,然后在Xcode中打开.xcworkspace文件,即可使用CocoaPods管理的包。
- Flutter的包管理工具runner是Flutter SDK中的一个工具,用于添加、移除和更新Flutter包,它能够自动下载和更新Flutter包,并将它们集成到项目中。Flutter的包管理工具与CocoaPods不同的是,它只管理Flutter的包依赖关系,不会管理iOS应用程序的其他第三方库。综上所述,使用CocoaPods可以方便地管理iOS项目中的所有依赖关系,包括管理Flutter包和其他第三方包,而使用Flutter的runner则只能管理Flutter的包依赖关系。选择哪种方式应根据具体项目的需求来决定。
Add Package添加包,
- 打开IOS登录 在 Firebase 控制台中,打开 Auth 部分。在 Sign in method(登录方法)标签页中,启用 Apple 提供方。 指定您在上一部分中创建的服务 ID。
(1)找到团队ID
(2)进入刚才创建的标识,复制团队ID
(3)回到Firebase平台,在你添加应用的这里添加团队ID
- 调用IOS登录
Future<UserCredential> signInWithApple() async {
final appleProvider = AppleAuthProvider();
if (kIsWeb) {
return await FirebaseAuth.instance.signInWithPopup(appleProvider);
} else {
return await FirebaseAuth.instance.signInWithProvider(appleProvider);
}
}
登录成功后,会返回数据,可以与上述Google登录成功一样,调用Firebase的方法来获取官方token传输给后端做校验用