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

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.

Related

Can we set user displayName in firebase using password authentication through flutter? [duplicate]

I can save the email and the password with Firebase Authentication. I also save this information with Cloud Firestore. But how can I add and save the displayName after registering?
my code:
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
// create a new document for the user with the uid
await DatabaseService(uid: user.uid)
.updateUserData('User', user.email, 'test.de/test.png', user.uid);
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
the register form button:
onPressed: () async {
if (_formKey.currentState.validate()) {
setState(() => loading = true);
dynamic result = await _auth
.registerWithEmailAndPassword(
email, password);
if (result == null) {
setState(() {
error = 'Valid email, please';
loading = false;
});
}
}
}
You can use updateProfile method given in the FirebaseUser class to update the name and photo url.
updateProfile({String displayName, String photoURL}).
For email you can use the different method
updateEmail(String newEmail) which is a async method.
Or to save the username directly into the firestore, after successful login you can use 'set' method of the FirebaseFirestore to save email, password and the username.
Here's the code if you want to save the Username together with the email and password
final FirebaseAuth _auth = FirebaseAuth.instance;
//register with email & password & save username instantly
Future registerWithEmailAndPassword(String name, String password, String email) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user;
user.updateProfile(displayName: name); //added this line
return _user(user);
} catch(e) {
print(e.toString());
return null;
}
}
late User userFirebase;
Future<UserCredential> userCredential =await //Your code signin or signup
await userCredential.then((UserCredential value) {
userFirebase = value.user!;
});
await userFirebase.updateDisplayName(event.name);
You can use updateDisplayName() and updatePhotoURL() methods on a User object to add the displayName/profile image to Firebase user.
final userCredential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//After creating a user in Firebase, we then are able to change name/pictue
await userCredential.user?.updateDisplayName(name);
await userCredential.user?.updatePhotoURL(imageUrl);
As of october 2021, updateProfile() is deprecated, and you should use updateDisplayName() and updatePhotoURL() instead.

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

Issues with code deprecation saving user info to firebase database

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

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

How can I resolve a problem with firebase registration?

I'm writing an application that have to register a user with firebase and than do the login. I wrote a function for the registration but the output give me this error:
PlatformException(error, Given String is empty or null, null)
This is the function:
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
Navigator.push(context, MaterialPageRoute(builder: (context) => Login()));
print(user);
return user;
} catch (e) {
print(e.toString());
return null;
}
}