Firebase Email Validation Flutter - flutter

I have this piece of code to sign up:
Future<String> signUp({String email, String password}) async {
try{
await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
return "Signed up";
} on FirebaseAuthException catch(e){
print("no se puede crear");
return e.message;
}
}
I need to implement the validation mail from firebase, this has been asked a lot and I came up with this when researching, some code is deprecated and its hard for me to find guidance:
Future<String> signUp({String email, String password}) async {
FirebaseUser user = await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
try {
await user.sendEmailVerification();
return user.uid;
} catch (e) {
print("An error occured while trying to send email verification");
print(e.message);
}
}
}
But cant figure how to implement it because it throws:
A value of type 'UserCredential' can't be assigned to a variable of type 'FirebaseUser'.

createUserWithEmailAndPassword doesn't return a FirebaseUser object. As you can see from the linked API documentation, it yields a UserCrediental object. That's what the error message is trying to tell you - you can't assign a UserCredential to a FirebaseUser typed variable.
If you wan to get a FirebaseUser object out of a UserCredential, you can simply use its user property.
UserCredential credential = await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = credential.user;

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.

Flutter - Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found

Flutter is not writing data to my firebase collection and has errors in the debug.
Steps to reproduce
https://www.youtube.com/watch?v=EA7973HI93E&list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC&index=18
Steps to reproduce the behavior:
Run the app,
register a user.
Expected behavior:
I expected that the user will be made and data to the collection added
the output
Ignoring header X-Firebase-Locale because its value was null. D/FirebaseAuth(17181): Notifying id token listeners about user ( fTnXUNwmPUajE9ybOeP3GLW0e392 ). D/FirebaseAuth(17181): Notifying auth state listeners about user ( fTnXUNwmPUajE9ybOeP3GLW0e392 ). W/DynamiteModule(17181): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found. I/DynamiteModule(17181): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0 W/ProviderInstaller(17181): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0. W/Firestore(17181): (24.4.0) [WriteStream]: (e9a00e8) Stream closed with status: Status{code=UNAVAILABLE, description=Channel shutdownNow invoked, cause=null}. W/DynamiteModule(17181): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
my auth.dart code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:my_app/models/user.dart';
import 'package:my_app/services/database.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// create MyUser object based on User
MyUser? _userFromFirebaseUser(User? user) {
return user != null ? MyUser(uid: user.uid) : null;
}
// auth change user stream
Stream<MyUser?> get user {
return _auth.authStateChanges().map(_userFromFirebaseUser);
}
//sign in anonymously
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
// sign in with email and password
Future SignInWithEmailAndPassword(String email, String password) async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
// register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
// create new document for the user with uid
await DatabaseService(uid: user?.uid)
.updateUserData('How do you feel', 'I am mad', 'angry');
return _userFromFirebaseUser(user);
} on FirebaseAuthException catch (e) {
print(e.toString());
return null;
}
}
// sign out
Future signOut() async {
try {
return await _auth.signOut();
} catch (e) {
print(e.toString());
return null;
}
}
}
My database.dart
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
// collection reference
final String? uid;
DatabaseService({this.uid});
final CollectionReference pollearnCollection =
FirebaseFirestore.instance.collection('Pollearn');
Future updateUserData(String question, String answer, String emotion) async {
Map<String, String> data = {
'question': question,
'answer': answer,
'emotion': emotion,
};
return await pollearnCollection.doc(uid).set(data);
}
}
I already tried the following:
turn the emulator on and off.
tried different emulator
updated google play services
turnt bluetooth off
turnt internet off and on
enabled sign in with mail and password
adding
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I hope you guys can help me. Thanks in advance!

updateDisplayName() not working after running createUserWithEmailAndPassword

I have a future method in a AuthService class to create new users with the inbuilt function createUserWithEmailAndPassword, but right after that I am trying to update the display name of that User? user but this never updates.
Future regEmailPass(String email, String password, String? username) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
await user?.updateDisplayName(username);
UserInApp? userInApp = _userFromFireBaseUser(user);
await DatabaseService(user: userInApp).firstTimeCreateDB(username!);
return userInApp;
} catch (e) {
print(e.toString());
return null;
}
}
I even tried using the await user.reload() or double checking if my user was null in the first place, but in every situation, the displayName was set to null in the firestore database.

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.