Login to Flutter Facebook Login - flutter

I'm having a problem with the facebook login with flutter.
I followed a lot of tutorials but it's from 2018, 2019, so it doesn't match the version of flutter_facebook_login: ^3.0.0.
the process works very well when I launch it redirects me to facebook I enter my details I log in as MyFacebookName, the problem is that when I click on Ok it redirects me to the login page and it does not register the user on my Firebase console. Here is the code
// Facebook connection configuration
static final FacebookLogin facebookSignIn = new FacebookLogin();
String _message = 'Login or logout by pressing the buttons below.';
Future<void> _login() async {
final FacebookLoginResult result =
await facebookSignIn.logIn(['email']);
switch (result.status) {
FacebookLoginStatus.loggedIn box:
final FacebookAccessToken accessToken = result.accessToken;
_showMessage(''')
Sign in!
Token: ${accessToken.token}
User id: ${accessToken.userId}
Expires: ${accessToken.expires}
Permissions: ${accessToken.permissions}
Declined permissions: ${accessToken.declinedPermissions}
''');
break;
checkbox FacebookLoginStatus.cancelledByUser:
_showMessage("login cancelled by user.");
break;
checkbox FacebookLoginStatus.error:
"Something went wrong during the login process."
"Here's the error Facebook gave us: ${result.errorMessage}");
break;
}
}
Future<Null> _logOut() async {
await facebookSignIn.logOut();
_showMessage('Logout.');
}
void _showMessage(String message) {
setState(() {
_message = message;
});
}
//connection button
_buildSocialBtn(
() {
_login();
},

Related

How to link phone number to already logged in email user which is using firebase

I want to link the already login user who has login from their email id when starting the website but after completing the signup process I want to add the phone number of the user but I am getting an error as firebase creates a new id every time when creating a new id after the phone OTP verification.
So, after some digging, I found out that there is a way to LINK already logged in the user with an email with a phone number.
But, the function is not working for me
here is my code for adding a phone number and then linking it with current user credentials.
sendOTP(String phoneNumber) async {
this.phoneNumber = phoneNumber;
FirebaseAuth auth = FirebaseAuth.instance;
print('${phoneCode}');
ConfirmationResult confirmationResult =
await auth.signInWithPhoneNumber('+${phoneCode}${phoneNumber}');
if (kDebugMode) {
print("OTP send to +${phoneCode} ${phoneNumber}");
}
return confirmationResult;
}
authenticateMe(ConfirmationResult confirmationResult, String otp) async {
UserCredential userCredential = await confirmationResult.confirm(otp);
signIn(AuthCredential userCredential) async {
//now link these credentials with the existing user
UserCredential? linkauthresult =
await existingUser?.linkWithCredential(userCredential);
print('linked');
}
firebaseOtp = otp;
}
here is my User existingUser = FirebaseAuth.instance.currentUser!; variable which is i am calling in init state
#override
void initState() {
super.initState();
existingUser;
print('this is current user from otp_container ${existingUser}');
}
and here is my button onPressed function
onPressed: () {
authenticateMe(
temp,
otpCodeController.text,
);
Future.delayed(const Duration(seconds: 3))
.then((value) {
if (!mounted) {
const CircularProgressIndicator();
}
setState(() {
if (otpCodeController.text ==
firebaseOtp) {
isAnimatedContainer =
!isAnimatedContainer;
} else {
setState(() {
verifyOtpcheck = !verifyOtpcheck;
});
}
});
});
},
and I am working on flutter web.

error when i click on google sign in flutter

When I click on the "google sign in" button and then instead of continuing I click on "cancel", this error comes out: "PlatformException (PlatformException (sign_in_canceled, com.google.GIDSignIn, The user canceled the sign-in flow., Null))."
The code is this:
Future<UserCredential?> signInWithGoogle() async {
try {
// Trigger the authentication flow
final GoogleSignInAccount? utenteGoogle = await GoogleSignIn().signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication? datiUtenteGoogle =
await utenteGoogle?.authentication;
// Create a new credential
final credenzialiGoogle = GoogleAuthProvider.credential(
accessToken: datiUtenteGoogle?.accessToken,
idToken: datiUtenteGoogle?.idToken,
);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance.signInWithCredential(credenzialiGoogle);
} catch (e) {
print(e);
return null;
}
}
I tried to catch the error but nothing

Firebase Google Sign In not working in Android for Flutter

I am trying to implement a Google Sign in feature for my Flutter app. I am using Firebase Authentication for this. I have generated SHA-1 fingerprint and added the same to the android app for this Firebase project. However, when I try to run the app in the emulator or any Android device, once the account is selected the account selection dialog closes and the app stays on the login screen. When I check my Firebase Authentication console, no new user is logged in or registered with the selected Google Account.
Note: Google signin works for my app in Firebase web, but doesn't work in Android.
My Code:
firebase_auth_methods.dart
//GOOGLE SIGN-IN
Future<void> loginWithGoogle(BuildContext context) async {
try {
if (kIsWeb) {
GoogleAuthProvider googleProvider = GoogleAuthProvider();
googleProvider
.addScope('https://www.googleapis.com/auth/contacts.readonly');
await _auth.signInWithPopup(googleProvider);
} else {
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
final GoogleSignInAuthentication? googleAuth =
await googleUser?.authentication;
if (googleAuth?.accessToken != null && googleAuth?.idToken != null) {
//create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken);
UserCredential userCredential =
await _auth.signInWithCredential(credential);
//if we want to SignUp with Google (not SignIn)
// if (userCredential.user != null) {
// if (userCredential.additionalUserInfo!.isNewUser) {}
// }
}
}
} on FirebaseAuthException catch (e) {
showSnackBar(context, e.message!);
}
}
signin_screen.dart
RoundedButton(
width: screenWidth * 0.1,
height: screenWidth * 0.1,
onTap: () {
context
.read<FirebaseAuthMethods>()
.loginWithGoogle(context);
//Navigator.pushNamed(context, "/home");
//Navigator.pop(context);
},
url:
"https://cdn.icon-icons.com/icons2/2631/PNG/512/google_search_new_logo_icon_159150.png",
),
What am I doing wrong, and how to solve this problem?

why Flutter login with facebook is not working

I'm trying to make a login screen with Facebook but end up with this error when I run my code. here is my code:
import 'package:facebook_login/services/auth_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
import 'package:auth/auth.dart';
class AuthBloc {
final authService = AuthService();
final fb = FacebookLogin();
Stream<User> get currentUser => authService.currentUser;
loginFacebook() async {
print('Starting Facebook Login');
final res = await fb.logIn(
permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email
]
);
switch(res.status){
case FacebookLoginStatus.Success:
print('It worked');
//Get Token
final FacebookAccessToken fbToken = res.accessToken;
//Convert to Auth Credential
final AuthCredential credential
= FacebookAuthProvider.getCredential(accessToken: fbToken.token);
//User Credential to Sign in with Firebase
final result = await authService.signInWithCredentail(credential);
print('${result.user.displayName} is now logged in');
break;
case FacebookLoginStatus.Cancel:
print('The user canceled the login');
break;
case FacebookLoginStatus.Error:
print('There was an error');
break;
}
}
logout(){
authService.logout();
}
}
when i run this i get this error message
Invalid depfile: C:\Users\Main\OneDrive\stuff\Documents\seltech\st\.dart_tool\flutter_build\7b28b646cfa2e7424746c78d0801893a\kernel_snapshot.d
Error: Couldn't resolve the package 'facebook_login' in 'package:facebook_login/services/auth_service.dart'.
Error: Couldn't resolve the package 'auth' in 'package:auth/auth.dart'.
lib/src/bloc/auth_bloc:1:8: Error: Not found: 'package:facebook_login/services/auth_service.dart'
import 'package:facebook_login/services/auth_service.dart';
there are more errors that pop up.
if you need more of the code I can send some more of it
it's so much it won't fit in here
all of the error I get is from the auth_block. I have another login page made on a separate screen.
I also have a manual login with firebase auth there .
With these packages on the pubspec:
flutter_facebook_auth: ^3.5.1
firebase_auth: ^3.1.0
firebase_core: ^1.6.0
And this function:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<String?> facebookSignin() async {
try {
final _instance = FacebookAuth.instance;
final result = await _instance.login(permissions: ['email']);
if (result.status == LoginStatus.success) {
final OAuthCredential credential =
FacebookAuthProvider.credential(result.accessToken!.token);
final a = await _auth.signInWithCredential(credential);
await _instance.getUserData().then((userData) async {
await _auth.currentUser!.updateEmail(userData['email']);
});
return null;
} else if (result.status == LoginStatus.cancelled) {
return 'Login cancelled';
} else {
return 'Error';
}
} catch (e) {
return e.toString();
}
}
I'm able to login with facebook on my app
don't forget to also follow the configuration steps for android/ios and facebook for developers console
enter image description here
#enable this Permissions and features
then it will work

Flutter Facebook Login Allowing to switch account

The app allows the user to sign in using Facebook, but I am having trouble with when the using wants to use a different Facebook account to sign in, this page will only show the continue button. Is there a way for the user to choose to use a different account for signing in?
Also, I have not really seem any error in the case for FacebookLoginStatus.error, what are some error handling that should be done to it?
I am new to flutter and coding, it will be helpful to point out if anything should be done differently or can be improve on.
onPressed: () async {
final facebookLogin = FacebookLogin();
final result = await facebookLogin.logIn(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
try{
final token = result.accessToken.token;
AuthCredential credential =
FacebookAuthProvider.getCredential(accessToken: token);
FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
if(user != null){
Navigator.pushReplacementNamed(context, Home.id);
}
} catch(e){
print(e);
}
break;
case FacebookLoginStatus.cancelledByUser:
print('cancelled');
break;
case FacebookLoginStatus.error:
print('error');
break;
}
},
having trouble with when the using wants to use a different Facebook account to sign in, this page will only show the continue button
I use FacebookLogin.logOut() to disconnect the user, just so the user can use a different account to login.
onPressed: () async {
final facebookLogin = FacebookLogin();
await facebookLogin.logOut(); // disconnect user
final FacebookLoginResult result =
await facebookLogin.logIn(['email', 'public_profile']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
try{
final token = result.accessToken.token;
AuthCredential credential =
FacebookAuthProvider.getCredential(accessToken: token);
FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
if(user != null){
Navigator.pushReplacementNamed(context, Home.id);
}
} catch(e){
print(e);
}
break;
case FacebookLoginStatus.cancelledByUser:
alertMessage(context, 'cancelled'); // show dialog
break;
case FacebookLoginStatus.error:
alertMessage(context, 'error'); // show dialog
break;
}
},
what are some error handling that should be done to it?
You may prompt user of the login status messages:
void alertMessage(context, String message) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text("Error"),
content: Text(message),
actions: [
FlatButton(
child: Text(S.of(context).ok),
onPressed: () {
Navigator.of(context).pop();
},
)
],
)
);
}
add to first of code to login facebook
await FacebookAuth.instance.logOut();