How to signIn with facebook in flutter? - facebook

How to signIn with facebook in flutter? I try like this but nothing appears. Something like the app froze but when I click back drop me 'CANCELED BY USER'.
How to make it work?
The problem is that nothing appears when you click only the application freezes and the only option is to go back and then throw it out 'CANCELED BY USER'.
var facebookLogin = FacebookLogin();
facebookLogin.logInWithReadPermissions(['email', 'public_profile']).then((result){
switch(result.status){
case FacebookLoginStatus.loggedIn:
FacebookAccessToken myToken = result.accessToken;
AuthCredential credential= FacebookAuthProvider.getCredential(accessToken: myToken.token);
FirebaseAuth.instance.signInWithCredential(credential).then((user){
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context) => Menu()
));
}).catchError((e){
print(e);
});
break;
case FacebookLoginStatus.cancelledByUser:
print('CANCELED BY USER');
break;
case FacebookLoginStatus.error:
// TODO: Handle this case.
break;
}
}).catchError((e){
print(e);
});

Related

How to navigate to home screen after successfully login in flutter?

I'm using the following code for login. But the problem is after successfully login it's not able to navigate to home page. If I navigate inside on pressed button then it automatically navigate to home and it will not check either user exists or not.
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailAddress,
password: password
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
I have called isUserLoggedIn function after pressing login button.
Change like this,
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailAddress,
password: password
);
//---------------------- add this part --------------
if (user != null) {
Navigator.of(context).pushNamedAndRemoveUntil(
'/home', (Route<dynamic> route) => false);
// route set to use this.
}
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
You can also use this method,
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
),
);
But If you use this, the user can back to login screen without signout. So, use pushNamedAndRemoveUntil method to navigate. It will remove all past routes. can't go back.
Read about pushNamedAndRemoveUntil
If you just want to check for the user and navigate based on that, HoRiz has answered.
But I would suggest that you implement a state management solution first like BLoC, Riverpod, etc. It will help you to manage all your data like user info or any other data.
Also if you are not using named routes, then you can use this instead to navigate:
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => NewScreen(),
),
);
Also, if want to learn all the things about routing then you can check Flutter's Oficial Website: Link
Navigator.pushReplacement(context,MaterialPageRoute(builder: (context)=>HomePage()));

Shows warning: Do not use BuildContexts across async gaps

if (_formKey.currentState!.validate()) {
try {
final newUser =
await _auth.createUserWithEmailAndPassword(
email: email.text, password: password.text);
if (newUser != null) {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => DashboardScreen(),
// ));
Navigator.pushNamed(context, 'dashboard');
}
setState(() {});
} catch (e) {
print(e);
}
}
},
this warning shown on Navigator.pushNamed(context,'dashboard');
trying to navigate to the dashboar screen.
1.
You have to put delay for other process can finish till then
Future.delayed(Duration(milliseconds: 200)).then((value) {
Navigator.pushNamed(context, 'dashboard')
});
2.
add if (!mounted) return; before Navigator.pushNamed(context, 'dashboard')
3.
Please put await before the navigator flutter because you used an asynchronously method call so you have to wait until the process is finished then you can navigate to your pages
await Navigator.pushNamed(context, 'dashboard');
4.
Also, you can store your navigator into a var and then use it.
final nav = Navigator.of(context);
nav.pushNamed('dashboard');

how to set default language for facebook in webview for flutter_facebook_login plugin

Im using flutter_facebook_login plugin https://pub.dev/packages/flutter_facebook_login
Future<Null> _facebookLogin() async {
facebookSignIn.loginBehavior = FacebookLoginBehavior.webViewOnly;
FacebookLoginResult result = await facebookSignIn.logIn([
'email',
'instagram_basic',
'pages_show_list',
'pages_read_engagement'
]);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
accessToken = result.accessToken;
_loginAsNewUser(accessToken.token);
break;
case FacebookLoginStatus.cancelledByUser:
Navigator.of(context).pop();
_auth.signOut();
break;
case FacebookLoginStatus.error:
simplestDialogBox(
context, 'An error Occured! Please try after some time.', () {
Navigator.of(context).pop();
});
_auth.signOut();
await _logOut();
break;
}
}
Here I'm using web View for login. So how to set default language as English for the login page?
I sometimes get Marathi, sometimes Hindi, which is local language. If i were to use use native view or browser, then the language will depend upon user preferences, but how to use default language EN in web View.

Login to Flutter Facebook Login

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();
},

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();