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

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
}

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

How do I delete a Firebase Storage file from URL

how can I get a button to delete a file from Firebase Storage using a URL as a reference. The URL is retrieved from a Firestore collection field called "fileUrl" using the Firebase Storage getDownloadUrl method.
When I try to delete, I receive an error and my app crashes.
Code:
onPressed: () async {
if (newsDataModel.get('fileUrl') != null) {
await FirebaseStorage.instance.refFromURL(newsDataModel.get('fileUrl')).delete();
} else {
return;
}
await newsDataModel.reference.delete().then((value) => Navigator.pop(context));
}
Error:
_AssertionError ('package:firebase_storage/src/firebase_storage.dart':
Failed assertion: line 112 pos 12: 'url.startsWith('gs://') || url.startsWith('http')':
'a url must start with 'gs://' or 'https://')
Realized that I had made a mistake. Some of the collections have fileUrl fields that are empty/null, so I was deleting collections that had null values and therefore returned an error.
New updated code:
onPressed: () async {
try {
if (hwDataModel.get('fileUrl') != null) {
await FirebaseStorage.instance.refFromURL(hwDataModel.get('fileUrl')).delete()
.then((value) => {
hwDataModel.reference.delete().then((value) =>
Navigator.pop(context))});
} else if (hwDataModel.get('fileUrl') == null) {
await hwDataModel.reference.delete().then(
(value) => Navigator.pop(context));
};
} on FirebaseException catch (error) {
Fluttertoast.showToast(
msg: error.message.toString(),
gravity: ToastGravity.TOP,
backgroundColor: Colors.red,
textColor: Colors.white);
}
},

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

NoSuchMethodError: The method '[]' was called on null. -FIREBASE Flutter

I'm trying to delete a FirebaseUser, and It returns a null error. I dunno what's wrong with my code.
can somebody answer with a proper explanation cause I'm new to this error!
The error:
D/FirebaseAuth(16061): Notifying id token listeners about user ( r6Nn5Gxxxxxxxxxxxxxxx ).
I/flutter (16061): Deletion error NoSuchMethodError: The method '[]' was called on null.
I/flutter (16061): Receiver: null
I/flutter (16061): Tried calling: []("user")
Here's how I'm trying to delete the user:
new FlatButton(
child: Text("Delete"),
onPressed: () async {
if (password.text.length == 0) {
showInSnackBar("Please enter your password");
} else {
FirebaseUser firebaseUser =
await FirebaseAuth.instance.currentUser();
String uid = firebaseUser.uid;
var credential = EmailAuthProvider.getCredential(
email: firebaseUser.email,
password: password.text);
var result = await firebaseUser
.reauthenticateWithCredential(credential);
try {
await result.user.delete();
} on PlatformException catch (e) {
print("///////// ${e.code}");
String errorCde = e.code;
if (errorCde == "ERROR_WRONG_PASSWORD") {
showInSnackBar("Wrong password! Please try agian.");
} else if (errorCde == "ERROR_TOO_MANY_REQUESTS") {
showInSnackBar(
"You've tried too many times, Please try again in a while!");
} else if (errorCde ==
"ERROR_NETWORK_REQUEST_FAILED") {
showInSnackBar(
"Please check your internet connection");
}
} catch (e) {
print("Deletion error $e");
showInSnackBar("Something went wrong");
}
}
},
),

Resources