Issues with code deprecation saving user info to firebase database - flutter

I have codes from former or deprecated flutter version on saving user info to firebase database.
But i have been trying to upgraded the code to the latest firebase_auth package but 'FirebaseUser' is flagged as an error.
void registerUser() async{
final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text).catchError((ex){
//Check Error and display message
PlatformException thisEx = ex;
showSnackBar(thisEx.message);
})).user;
// check if user registration is successful
if(user != null){
DatabaseReference newUserRef = FirebaseDatabase.instance.reference().child('users/${user.uid}');
Map userMap = {
'fullname': fullNameController.text,
'email': emailController.text,
'phone': phoneController.text,
};
newUserRef.set(userMap);
Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false);
}
}
I have tried upgrading the codes my self but, it doesn't look and behave like before. here is my code but i need some help.
Thanks in advance...
void registerUser() async{
//final UserCredential user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text));
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
if (userCredential != null) {
DatabaseReference newUserRef = FirebaseDatabase.instance.reference()
.child('users/${userCredential.toString}');
M
}
}
on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}

Related

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<UserCredential>', is a potentially non-nullable type

I am building a flutter app and I am trying to create a method that will enable users to be registered in Firebase as well as storing their data in Firestore. I am getting an error where the body is returning null. I know the method has to return Usercredential somehow but I am a bit stuck. Please may anyone assist.
Here's my code:
void validateAndSubmit() async {
if (validateAndSave()) {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: _email, password: _password)
.then((userCredential) {
FirebaseFirestore.instance.collection('users').doc(userCredential.user!.uid).set({
"uid": userCredential.user!.uid,
'Name': _name,
'userName': _userName,
'email': _email,
});
}
);
Navigator.pushNamed(context, '/home');
print('Registered user: ${userCredential.user}');
const snackBar =
SnackBar(content: Text('User has been successfully registered!'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
} on FirebaseAuthException catch (e) {
print('Error: $e');
}
}
}
This error is due to chances of userCredential being null, i.e Firebase not being able to create a user with given credentials. So it'd be better to await FirebaseAuth as
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email, password: _password)
and then check if user returned is null by using an if statement, then continue with the above Firestore part.
Easier way, add nullcheck here:
...
.then((userCredential!) {
...
This happened because you use ! on userCredential which may be null, You can change your code to this:
try {
UserCredential? userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: _email, password: _password);
if (userCredential != null) {
FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user!.uid)
.set({
"uid": userCredential.user!.uid,
'Name': _name,
'userName': _userName,
'email': _email,
});
Navigator.pushNamed(context, '/home');
print('Registered user: ${userCredential.user}');
const snackBar =
SnackBar(content: Text('User has been successfully registered!'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
} on FirebaseAuthException catch (e) {
print('Error: $e');
}

error : display a red line under this statement _userFromFirebaseUser(userCredential.user);

hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
return userCredential != null
? UserModel(
id: userCredential.uid,
bannerImageUrl: '',
name: '',
email: '',
profileImageUrl: '')
: null;
}
Stream<UserModel?> get userCredential {
return auth
.authStateChanges()
.map((userCredential) => _userFromFirebaseUser(userCredential!));
}
Future SignUp(email, password) async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
print("valid");
formdata.save();
try {
UserCredential userCredential =
(await auth.createUserWithEmailAndPassword(
email: myemail!, password: mypassword!));
FirebaseFirestore.instance
.collection('Users')
.doc(userCredential.user!.uid)
.set({'name': email, 'email': email});
_userFromFirebaseUser(userCredential.user);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Navigator.of(context).pop();
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Navigator.of(context).pop();
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
} else {}
}
and the red line appears on this line _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me
userCredential.user is User? not User
change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
return ....
}

Firebase authentication! I'm able to move to home page even if i enter a non registered user

I've successfully added firebase to my flutter2.0 project. I've enables authentication also.I'm able to register a new user also. But the logic to move to home page after authentication is not working. I'm able to login even if I enter a wrong user. I want if I enter proper user then I should navigate to home page, but if the user is not registered it one should not be able to navigate to next page. ie..the basic use of authentication.
But it's not happening here. I'm able to navigate to next place even if I enter wrong user.
Future signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
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.');
}
}
}
Future newAccount(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e.toString());
}
}
}
//this is how I can this function and try to navigate to next page.
void logMeIn() {
if (formKey.currentState!.validate()) {
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();
}));
});
}
}**strong text**
signInWithEmailAndPassword returns a UserCredential object.
In your logic, you are using .then((value) {...etc})
This value is the result of signInWithEmailAndPassword.
Try changing your logic to this:
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
if(value.user ==null) return "Error in authentication"; // this will prevent your function form going further down the navigation if the usercredential doesn't have a valid user.
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();

Flutter how to listen for email verification before user can sign in - firebase

My app allows the user to register and sends an email for verification. However i have a problem where the user can sign in with the new account whether the email is verified or not. I have looked and cannot find a solution to this bearing in mind i'm new to flutter
My Auth Code
Future<String> signIn(String email, String password) async {
AuthResult result = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
if (user.isEmailVerified) {
return user.uid;
} else {
return null;
}
}
Future<String> signUp(String email, String password) async {
AuthResult result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
try {
await user.sendEmailVerification();
return user.uid;
} catch (e) {
print("An error occurred while trying to send email verification");
print(e.message);
}
}
sign in method
try {
if (_isLoginForm) {
userId = await widget.auth.signIn(_email, _password);
print('Signed in: $userId');
} else {
userId = await widget.auth.signUp(_email, _password);
//widget.auth.sendEmailVerification();
_showVerifyEmailSentDialog();
print('Signed up user: $userId');
}
setState(() {
_isLoading = false;
});
if (userId.length > 0 && userId != null && _isLoginForm) {
widget.loginCallback();
}

Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: flutter/textinput. Response ID: 0

I am trying to create a user in Firebase using Flutter, but when tried to send email and password the app crashes.
and this is the code snippet:
void validateAndSubmit() async {
if (validateAndSave()) {
try {
if (_formType == FormType.login) {
AuthResult result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email:_email ,
password: _password);
FirebaseUser user = result.user;
print('Login page');
print('UID is : ${user.uid}');
} else {
AuthResult result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: _email ,
password: _password);
FirebaseUser user = result.user;
print('Register Page');
print('UID is : ${user.uid}');
}
} catch (e) {
print('Error: $e');
}
}
}
You shouldn't create a new user when you're logging in!
Just call signInWithEmailAndPassword(email: _email, password: _password) which returns an AuthResult object.