Flutter getting unknown error from firebase authentication service - firebase

I have released my first app to google play and opened it for several test users.
I am using Firebase Authentication service for managing users.
When my test users try to signup (by email and password), they get an unknown error.
Are there any special changes I need to do before releasing my app?
My functionality is quite simple so I really don't know why they get an error.
Thank you in advance.
Error:
"[firebase_auth/unknown] There was an error while initializing the connection to the GoogleApi: java.lang.NoSuchMethodError: No static method isAtLeastR()Z in class La/d/g/a; or its super classes (declaration of 'a.d.g.a' appears in /data/app/com.omertab.appname--WeJcqqlq_1NPgpgJc96JQ==/base.apk)"
Instance:
final _auth = FirebaseAuth.instance;
My functionality:
MaterialButton(
onPressed: () async {
_showSpinner = true;
try {
final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (newUser != null) {
await _fireStore.collection('users').add({
'email': email,
'uId': _auth.currentUser.uid
});
Navigator.pushNamed(context, HomePage.screenId);
_showSpinner = false;
}
} on FirebaseAuthException catch (e) {
_showSpinner = false;
print(e.code);
if(e.code == "invalid-email") {
print("INVALID EMAIL");
setState(() {
signupError = "Invalid mail";
});
} else if(e.code == "invalid-password") {
print("INVALID PASS");
setState(() {
signupError = "Invalid password";
});
} else if(e.code == "weak-password") {
setState(() {
signupError = "Please choose a stronger password";
});
} else if(e.code == "unknown") {
setState(() {
signupError = "Unknown error occurred";
});
}
}
},
minWidth: 200.0,
height: 42.0,
child: Text(
'Signup',
style: TextStyle(color: Colors.white),
),

Issue solved.
I implemented
implementation("com.google.android.gms:play-services-base:17.6.0"){ force = true }
to build.gradle

Not the problem described, but it might help someone. I was getting a different error:
[firebase_auth/unknown] com.google.firebase.FirebaseException: An internal error has occurred. [ CONFIGURATION_NOT_FOUND ]
I've solved it by activating the authentication service in the Firebase console.

Related

await user.sendEmailVerification - Unexpected internal error (Sending/Creating sign in email link)

I am just starting out with flutter and i'm using Firebase as my back-end authentication. I have been having no issues creating user accounts/logging in/logging out. But now I am setting up email verification and everytime I call user.sendEmailVerification it returns the following:
An internal error has occurred, print and inspect the error details for more information.
I expected a email in the user's inbox but nothing occurs. I have enabled email sign in.
And the domain is registered. It returns that error and does nothing else.
Here is the async function I am calling.
Future<void> _createAccount() async {
if (!_makeSureOfValidCredentials()) {
return;
}
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text.trim(), password: passwordController.text.trim());
var user = FirebaseAuth.instance.currentUser;
if (user != null) {
await user.sendEmailVerification(ActionCodeSettings(
url: 'https://__url__.____',
handleCodeInApp: true,
iOSBundleId: iosBundleIdentifier,
androidPackageName: androidBundleIdentifier,
androidMinimumVersion: '18',
androidInstallApp: true,
));
print('sent verification email');
}
Navigator.push(context, MaterialPageRoute(builder: (_) => const SignupEmailVerify() ));
} on FirebaseAuthException catch (e) {
_displayError(e.message as String);
print(e.stackTrace);
print(e.message);
return;
} catch (e) {
_displayError("An unexpected error has occurred, please try again later.");
return;
}
}
Screenshot of sing in on firebase email/password

Cannot set user display name in my flutter app

I have been trying to set my user display name upon signup. All of the solution I have found in stackoverflow suggest to use updateProfile(). But it is deprecated, and flutter docs say to use updateDisplayName instead.
I have tried to implement it in this way,
void donorSignUp() async {
try {
showLoading();
await auth
.createUserWithEmailAndPassword(
email: email.text.trim(), password: password.text.trim())
.then((result) {
String _userId = result.user!.uid;
_addDonorToFirestore(_userId);
_clearSignUpControllers();
result.user?.updateDisplayName(donorModel.value.name);
});
} catch (e) {
debugPrint(e.toString());
Get.snackbar('Sign Up Failed', 'Try again');
}
}
However, when I try to show it in my Drawer, calling user?.displayName it doesn't show anything. I have also checked that donorModel.value.name consists a string value, I know its not null. What should I do?
the function donorSignUp() is called inside an elevatedbutton,
child: ElevatedButton(
child: Text(
'Register',
style: buttonFontSansita,
),
onPressed: () {
if (authController
.signupFormKey.currentState!
.validate()) {
authController.donorSignUp();
}
},
The recommended way to always have the real-time auth state is to use the authStateChanges listener:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
You can read more about it here. Ideally you can use a Provider to make the data available through the whole app.

Firebase Authentication with Flutter not working

I am trying to create a signup page which should give an error message if user with particular email id already exist. But it's not working.
signUp() {
if (formkey.currentState!.validate()) {
Map<String, String> userDataMap = {
"name": usernameC.text,
"email": emailC.text
};
setState(() {
isLoading = true;
});
authMethods.signUp(emailC.text, passwordC.text).then((value) {
databaseMethods.uploadUserData(userDataMap);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => ChatRoom()));
});
}
}
It calls the signUp() function from auth.dart given below
UserData? _userFromFirebase(User? user) {
return user != null ? UserData(userid: user.uid) : null;
}
Future signUp(String email, String pass) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: pass);
User? user = result.user;
return _userFromFirebase(user);
} catch (e) {
print(e}
}
Every time I signup with same email it doesn't give any error.
If you sign up with the same email you should get this message:
[firebase_auth/email-already-in-use] The email address is already in use by another account.
I use print(e.hashCode) and then use this hash code to show an error message.
Ok I tried this method and it worked out. Just added null check for the "value" attribute in.
authMethods.signUp(emailC.text, passwordC.text).then((value)
It was returning null without any other message. That's why I was unable to see the error.

Flutter and Firebase admin and normal user login

hello i am new to flutter and firebase and i have a field in the user document that is called admin and it's a boolean , i want to check this boolean in the sign in functionality .
what i came up so far is this :
onPressed: () async {
if (_formKey.currentState.validate()) {
if (!await user.signIn(_email.text, _password.text)) {
toast("Signin Faild");
} else {
if(await _firestore.collection('users').doc(_auth.currentUser.uid).get().)
changeScreenReplacement(context, HomePage());
toast("Signedin successfully");
}
}
},
i don't know what to do in this part :
if(await _firestore.collection('users').doc(_auth.currentUser.uid).get().)
i want here to check the field if it's equal to true or false how can i do this ?
If you want to check if the user return true or false, you can do as following:
onPressed: () async {
if (_formKey.currentState.validate()) {
if (!await user.signIn(_email.text, _password.text)) {
toast("Signin Faild");
} else {
FirebaseUser user = await _auth.currentUser();
DocumentReference document = await _firestore.collection('users').doc(user.uid).get()
if(document.data['admin'] == true)
changeScreenReplacement(context, HomePage());
toast("Signedin successfully");
}
}
},
You can also check the Flutter Documentation

Why My Update Email is not WORKING, Firebase and Flutter?

I want to build a function that update the user email in firebase so this is what I did:
1- checked if there is internet.
2- do user.updateEmail with the email I got from firestore after I uploaded it in the sign Up and It can't be null because I used it down and it also prints the error :
NoSuchMethodError: The method 'updateEmail' was called on null.
I/flutter ( 9769): Receiver: null
I/flutter ( 9769): Tried calling: updateEmail("omarkaram1st#gmail.com")
see It got the email but somehow it can't send an email;
Code :
switchAccount() async {
try {
final user = await _auth.currentUser();
final result = await InternetAddress.lookup('google.com');
try {
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
user.updateEmail(email);
AwesomeDialog(
btnOkText: 'Ok',
context: context,
headerAnimationLoop: false,
dialogType: DialogType.INFO,
animType: AnimType.BOTTOMSLIDE,
title: 'Info',
desc: 'A Reset Email Has Been Sent To $email',
btnOkOnPress: () {},
)..show();
}
} catch (e) {
print(e);
}
} on SocketException catch (_) {
AwesomeDialog(
btnOkText: 'Retry',
context: context,
headerAnimationLoop: false,
dialogType: DialogType.ERROR,
animType: AnimType.BOTTOMSLIDE,
title: 'Error',
desc:
'Make Sure That You Have an Internet Connection Before Pressing Retry',
btnOkOnPress: () =>
Navigator.pushReplacementNamed(context, '/HomePage'),
)..show();
}
}
It looks like user is null in your call to user.updateEmail(email). We can't say why that is from the code you shared, but the quick way to prevent the error is to check for null after calling await _auth.currentUser().
final user = await _auth.currentUser();
if (user != null) {
final result = await InternetAddress.lookup('google.com');
try {
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
user.updateEmail(email);
...
}
} catch (e) {
print(e);
}
}
else {
... do something relevant when no user is signed in
}

Resources