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

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

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 Firebase try catch does not fire

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;
}
}

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

Couldn't catch new FlutterFire Firebase Auth

I've been trying to catch exception from the new https://firebase.flutter.dev/ Firebase Auth and failed.
Not sure what went wrong, here is my code for signIn with email and password function:
try {
UserCredential userCredential = await _firebaseAuth
.signInWithEmailAndPassword(email: email, password: password);
if (userCredential != null) {
_user = userCredential.user;
}
} on FirebaseAuthException catch (e) {
print(e.code);
} on PlatformException catch (e) {
print(e.message);
} catch (e) {
print(e.toString());
}
return _user;
}
Have you check at firebase console authentication whether your user is listed there or not.
If it not that's the problem, you can add new user at the console and try again login with email and password u just add.
You can use something like this,
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} 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.');
}
}
More Error Codes: https://firebase.google.com/docs/reference/js/firebase.auth.Auth#error-codes_12

Resources