Flutter Firebase try catch does not fire - firebase

When using firebase auth and type not registered email,
although I used try - catch, that does not fire.
fAuth.signInWithEmailAndPassword definitely throw PlatformException but that code does not catch that.
I suffered this problem about 2days..... please help me
Future<bool> signInWithEmail(String email, String password) async {
try {
var result = await fAuth.signInWithEmailAndPassword(
email: email, password: password);
if (result != null) {
setUser(result.user);
FirebaseFirestore.instance.collection("User").doc(_user.uid).get().then((doc) {
info.set(
name: doc["name"],
email: doc["email"],
phoneNumber: doc["phoneNumber"],
follower: doc["follower"],
following: doc["following"],
like: doc["like"],
review: doc["review"],
visited: doc["visited"],
favorite: doc["favorite"],
);
print(doc['name']);
notifyListeners();
});
return true;
}
return false;
} on PlatformException catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
} on Exception catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
} catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
}
}

Related

Not able to catch error of changing Firebase User email

Since hours I have an Problem with my method. When trying to update use email and the email really exists its works fine. But when I pasting just any sh-- its giving me an error in console but not returning anything . Please help
This is my method
//update in with passwort and email
Future updateemail2(String email, String password, String newemail) async {
try {
UserCredential authResult =
await _auth.currentUser.reauthenticateWithCredential(
EmailAuthProvider.credential(
email: email,
password: password,
),
);
User user = authResult.user;
if (user != null) {
user.verifyBeforeUpdateEmail(newemail);
// user.sendEmailVerification();
}
// user?.emailVerified;
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email ist nicht gültig';
}
case 'email-already-in-use':
{
return 'Email bereits registriert';
}
case 'wrong-password':
{
return 'Passwort ist nicht gültig';
}
case 'internal-error':
{
return "internal error";
}
default:
{
return 'Unexpected Error';
}
return null;
}
}
return null;
}
Im calling it like that
buildupdate(context, userData, user) async {
if (_formKey.currentState.validate()) {
String authError4 = await _auth.updateemail2(
userData.email, userData.password, _currentemail);
if (authError4 != null) {
setState(() {
showerror = true;
error = authError4;
});
} else {
print("halts maul");
}
This is the error which im not able to catch

Flutter User creation and Signing in

Here is my code
I am trying to run this code with no avail.
import 'package:firebase_auth/firebase_auth.dart';
class AuthClass {
FirebaseAuth auth = FirebaseAuth.instance;
//create account
Future<String> createAccount(
{required String email, required String password}) async {
try {
await auth.createUserWithEmailAndPassword(
email: email, password: password);
return "Account created";
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
return 'The password provided is too weak.';
} else if (e.code == 'email-already-in-use') {
return 'The account already exists for that email.';
}
} catch (e) {
return 'Error Occured';
}
}
//sign in user
Future<String> signIn(
{required String email, required String password}) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
return 'No user found for that email.';
} else if (e.code == 'wrong-password') {
return 'Wrong password provided for that user.';
}
}
}
// reset password
Future<String> resetPassword({
required String email,
}) async {
try {
await auth.sendPasswordResetEmail(
email: email,
);
return 'Email Sent';
} catch (e) {
return 'Error Occured';
}
}
//sign out
void signOut() {
auth.signOut();
}
}
I need some help I am getting this error,
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
Future signIn(...) "signIn"
Future createAccount(...) "createAccount"
is where i am getting the error
try on catch blocks work like this.
try executes code. If that fails, it throws an Exception.
Now, that Exception can be of many types and using on and catch together we can catch a specific exception and get that value inside e.
But the on FirebaseAuthException catch (e), only catches Exceptions of type FirebaseAuthException.
So, in a case where your try block throws something else, maybe NumberException, then it won't be caught.
For catching all other types of Exceptions, you need to add another catch block.
Like this,
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
return 'No user found for that email.';
} else if (e.code == 'wrong-password') {
return 'Wrong password provided for that user.';
}
} catch (e) {
return 'Unknown Error.'; // Change this to whatever you want.
}
Think of the try like an if block. Then your on FirebaseAuthException catch (e) would be an if else block. But you also need to handle the else block and that is your catch (e).
Hope it makes sense.

Flutter // I can't catch the Exceptions (Firebase app)

I have a big problem but I know it is small for humankind. I'm trying email and password Authentication on Firebase with Flutter.
But I always get some exceptions. (PlatformException and FirebaseAuthExceptions).
`
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password))
.user;
Get.to(HomeScreen());
Get.snackbar("Oturum açıldı", "message");
} else {
Get.snackbar("Oturum zaten açık", "message");
Get.to(HomeScreen());
}
} on PlatformException catch (e) {
_error = e.message;
Get.snackbar("başlık", e.message);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("başlık", e.message);
}
}
`
Also, I'm using the getX package. I tried everything but I can't catch the exceptions. When I call this method from UI, the SDK (VSCode) pausing debugging app and show exceptions in red alert.
I read a lot of documents about this situation but I couldn't found a solution.
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password))
.user;
Get.off(HomeScreen());
Get.snackbar("Oturum açıldı", "message", backgroundColor: Colors.teal);
} else {
Get.off(HomeScreen());
}
} on FirebaseAuthException catch (e) {
_error = e.code;
Get.snackbar("Giriş Yapılırken Hata",
"Giriş ypaılırken hata ile karşılaşıldı. Kod: ${e.code}",
snackPosition: SnackPosition.BOTTOM, snackStyle: SnackStyle.FLOATING);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("Hata",
"Sunucu beklenmedik bir hata ile karşılaştı. Detaylı bilgi: ${e.message}");
}
I just did something like this and solve my problem. Still I dont understand where is different catch things. Thanks for all help. <3
Ok, you can try to use the catch method after signInWithEmailAndPassword like this:
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password)
// Here, you can handle the error!
.catchError((error) {
print("The error message is: ${error.message}");
Get.snackbar("başlık", error.message);
})
.user;
Get.to(HomeScreen());
Get.snackbar("Oturum açıldı", "message");
} else {
Get.snackbar("Oturum zaten açık", "message");
Get.to(HomeScreen());
}
} on PlatformException catch (e) {
_error = e.message;
Get.snackbar("başlık", e.message);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("başlık", e.message);
}
}

displayname returns null after registration on flutter

Display name returns null right after registration. However, if i login with the same email id, the display name shows up magically. Looked up some of the answers here but didn't find anything relevant to implementation in flutter.
My Code:
Future createUserWithEmailAndPassword(
String email, String password, String name) async {
try {
UserCredential userCredential = await _auth
.createUserWithEmailAndPassword(email: email, password: password);
await userCredential.user.updateProfile(displayName: name);
print(userCredential.user.displayName);
User user = userCredential.user;
db.setProfileonRegistration(user.uid, name);
return _userFromFireBase(userCredential.user);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
return null;
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
The rest of the function is not waiting for line 6, but you are expecting the code is waiting for successful execution of that line before continue
Instead of using
await userCredential.user.updateProfile(displayName: name);
Try using this
Future createUserWithEmailAndPassword(
String email, String password, String name) async {
try {
UserCredential userCredential = await _auth
.createUserWithEmailAndPassword(email: email, password: password);
userCredential.user.updateProfile(displayName: name).then((_) {
print(userCredential.user.displayName);
User user = userCredential.user;
db.setProfileonRegistration(user.uid, name);
return _userFromFireBase(userCredential.user);
});
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
return null;
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
It will wait until
userCredential.user.updateProfile(displayName: name)
Future resolves and then continues with the rest of the code in the .then block

How do I tell the difference between exceptions in flutter authenticating with Firebase?

I have Firebase a sign in for my app. I want to report exceptions to the user so he can correctly login. It is email and password sign in signInWithEmailAndPassword(_email, _password). Testing I can create two exceptions which are self explanatory
1/ Error: PlatformException(exception, There is no user record corresponding to this identifier. The user may have been deleted., null)
2/ Error: PlatformException(exception, The password is invalid or the user does not have a password., null)
I'm using a try catch block to catch the error. Here is my code:
void validateAndSubmit() async {
FocusScope.of(context).requestFocus(new FocusNode());
if (validateAndSave()) {
try {
var auth = AuthProvider.of(context).auth;
FirebaseUser user =
await auth.signInWithEmailAndPassword(_email, _password);
print('Signed in: ${user.uid}');
Navigator.pop(context);
widget.loginCallback(user);
} catch (e) {
print('Error: $e');
setState(() {
_showMessage=true;
});
}
}
}
I want to give a different message depending on the exception. But there doesn't seem to be any code associated with the exception.
You can catch different kind of exceptions, for each exceptions, you can check the code
void validateAndSubmit() async {
FocusScope.of(context).requestFocus(new FocusNode());
if (validateAndSave()) {
try {
var auth = AuthProvider.of(context).auth;
FirebaseUser user =
await auth.signInWithEmailAndPassword(_email, _password);
print('Signed in: ${user.uid}');
Navigator.pop(context);
widget.loginCallback(user);
} on FirebaseAuthInvalidUserException catch (e) {
print('FirebaseAuthInvalidUserException: $e');
if (e.code === 'ERROR_USER_NOT_FOUND') {
setState(() {
_showMessage=true;
});
} else {
// do something
}
}
} on FirebaseAuthInvalidCredentialsException catch (e) {
// do something InvalidCredentials
} catch (e) {
// do something else
}
}
You can check e.code.
Check out native firebase documentation. It has values like 'ERROR_USER_NOT_FOUND'

Resources