Flutter Facebook Login with Firebase 使用 flutter_login_facebook 0.2.1
Posted
技术标签:
【中文标题】Flutter Facebook Login with Firebase 使用 flutter_login_facebook 0.2.1【英文标题】:Flutter Facebook Login with Firebase by using flutter_login_facebook 0.2.1 【发布时间】:2020-11-29 22:02:46 【问题描述】:我是 Flutter 和 Dart 的新手,我正在使用 Google、Apple、FB 和 Email&Password 构建登录结构。
我对 FB 集成有一些问题。我正在使用这个依赖:https://pub.dev/packages/flutter_login_facebook 还要检查他们的gitHub 和更好的Medium article。
问题是他们不提供 Firebase 集成,而且我没有足够的经验来介绍它。 这是他们的代码:
import 'package:flutter/material.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget
final fb = FacebookLogin();
@override
_MyAppState createState() => _MyAppState();
class _MyAppState extends State<MyApp>
@override
Widget build(BuildContext context)
return MaterialApp(
home: Scaffold(
body: Center(
child: OutlineButton(
child: Text('Log In'),
onPressed: () async
final fb = widget.fb;
// Log in
final res = await fb.logIn(permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email,
]);
// Check result status
switch (res.status)
case FacebookLoginStatus.Success:
// Logged in
// Send this access token to server for validation and auth
final accessToken = res.accessToken;
print('Access Token: $accessToken.token');
// Get profile data
final profile = await fb.getUserProfile();
print('Hello, $profile.name! You ID: $profile.userId');
// Get email (since we request email permission)
final email = await fb.getUserEmail();
// But user can decline permission
if (email != null) print('And your email is $email');
break;
case FacebookLoginStatus.Cancel:
// User cancel log in
break;
case FacebookLoginStatus.Error:
// Log in failed
print('Error while log in: $res.error');
break;
,
),
),
),
);
现在,我想将该代码与我用于 Google 和其他人的 Firebase 身份验证集成。 这是我的代码:wrapper.dart
class Wrapper extends StatelessWidget
@override
Widget build(BuildContext context)
final user = Provider.of<User>(context);
if (user == null)
return Home(); <-- widget with all the logins buttons
else
return Stores(); <-- widget when they are signed in
home.dart*
class Home extends StatefulWidget
@override
_HomeState createState() => _HomeState();
class _HomeState extends State<Home>
final AuthService _auth = AuthService();
bool loading = false;
bool isios = UniversalPlatform.isIOS;
bool isandroid = UniversalPlatform.isAndroid;
bool isWeb = UniversalPlatform.isWeb;
final welcomeText = 'Welcome';
final subtitle = 'Make grocery chores easier';
final anonymousButtonText = 'Skip';
@override
Widget build(BuildContext context)
return loading
? Loading()
: Stack(children: [
AuthLayout(),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Center(child: Text(welcomeText)),
backgroundColor: Colors.transparent,
),
body: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
// Facebook SignIn
<!-- [FB Button should go here, same structure as the Google button below] -->
// Google SignIn
Padding(
padding: EdgeInsets.all(8.0),
child: new MaterialButton(
onPressed: () async
setState(() => loading = true);
dynamic result =
await _auth.signInGoogle();
if (result == null)
setState(()
loading = false;
);
print(
'error signin in'); // create error page with SnackBar
else
print('Signed In Google');
print(result.uid);
,
child: SignInGoogleBtn())),
])))))
]);
authService.dart
class AuthService
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
// Create user object based on FirebaseUser
User _userFromFirebaseUser(FirebaseUser user)
return user != null ? User(uid: user.uid) : null;
// Auth change user stream
Stream<User> get user
return _auth.onAuthStateChanged.map(
_userFromFirebaseUser);
// SignIn with Facebook
// --- HELP HERE --- The structure should be similar to the Google Auth below
Future signInFacebook() async
// SignIn with Google
Future signInGoogle() async
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleSignInAuthentication.idToken,
accessToken: googleSignInAuthentication.accessToken);
try
AuthResult result = (await _auth.signInWithCredential(credential));
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
catch (e)
print(e.toString());
return null;
// SignOut
Future signOut() async
try
return await _auth.signOut();
catch (e)
print(e.toString());
return null;
该行为应与 Google btn 相同。当他们点击时,我们通过传统的 FB 身份验证,一旦它通过了身份验证,它应该回头查看 wrapper.dart
文件,其中 IF 语句将确定 user
是否为空。如果通过身份验证,该语句会将用户重定向到 stores
小部件。
非常感谢任何帮助 乔
【问题讨论】:
【参考方案1】:更新: 感谢建立这种依赖关系的人(超级明星),我找到了解决问题的方法。
authService.dart
Future signInFacebook() async
try
final facebookLogin = FacebookLogin();
// bool isLoggedIn = await facebookLogin.isLoggedIn;
final FacebookLoginResult result = await facebookLogin.logIn(
permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email,
],
);
switch (result.status)
case FacebookLoginStatus.Success:
String token = result.accessToken.token;
final AuthCredential credential =
FacebookAuthProvider.getCredential(accessToken: token);
await _auth.signInWithCredential(credential);
break;
case FacebookLoginStatus.Cancel:
break;
case FacebookLoginStatus.Error:
print(result.error);
break;
return true;
catch (error)
return false;
home.dart
.....
Padding(
padding: EdgeInsets.all(8.0),
child: new MaterialButton(
onPressed: () async
setState(() => loading = true);
dynamic result = await _auth.signInFacebook();
if (result == null)
setState(()
loading = false;
);
print('error signin in'); // create error page with SnackBar
else
print('Signed In Facebook');
,
child: signInFacebookBtn()
)
), .....
【讨论】:
以上是关于Flutter Facebook Login with Firebase 使用 flutter_login_facebook 0.2.1的主要内容,如果未能解决你的问题,请参考以下文章
flutter_facebook_login CocoaPods 依赖错误
Flutter Login with Facebook 返回构建错误
如何连接facebook、firebase和flutter?